单例模式

import threading
import os
import configparser

"""
饿汉式,
在创建的时候就会生成唯一的单例实例。

不能延迟加载。
"""


class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance


"""
饿汉式  使用装饰器
"""


def singleton(cls):
    _instance = {}

    def _singleton(*args, **kwargs):
        if not _instance[cls]:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]

    return _singleton


@singleton
class Test(object):
    def __init__(self, x):
        self.x = x


"""
懒汉式,线程不安全的
"""


class Singleton2(object):
    _instance = None

    def __init__(self, *args, **kwargs):
        if not self._instance:
            print("实例未创建")
        else:
            print("实例已创建")

    @classmethod
    def get_instance(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton2, cls).__new__(cls, *args, **kwargs)
        return cls._instance


"""
饿汉式,线程安全的
"""


class Singleton3(object):
    _instance = None

    _instance_lock = threading.Lock()

    @classmethod
    def get_instance(cls, *args, **kwargs):
        if not cls._instance:
            with cls._instance_lock:
                if not cls._instance:
                    cls._instance = super(Singleton3, cls).__new__(cls, *args, **kwargs)
        return cls._instance


# 应用
class Config(object):
    """
    创建配置文件单例类
    """
    _instance_lock = threading.Lock()

    def __init__(self):

        root_dir = os.path.abspath(os.path.dirname(__file__))
        case_dir = os.path.join(root_dir, "conf.ini")

        self.cf = configparser.ConfigParser()
        self.cf.read(case_dir)

    def __new__(cls, *args, **kwargs):

        if not hasattr(Config, "_instance"):
            with Config._instance_lock:
                if not hasattr(Config, "_instance"):
                    Config._instance = object.__new__(cls)
        return Config._instance

    def get_config(self, sectionname, key):
        """
        获取配置文件内,对应sectionname内,key对应的value
        """
        var = self.cf.get(sectionname, key)
        return var


if __name__ == '__main__':
    c1 = Config()
    val = c1.get_config("base", "region")
    print(val)

    c2 = Config()
    val2 = c2.get_config("base", "zone")
    print(val2)

你可能感兴趣的:(单例模式)