Python:设计模式介绍--单例模式

单例模式

1、单例是只有一个实例
2、通过静态字段+静态字段伪造出一个单例效果
3、什么时候用:当所有实例中封装的数据相同时,创建单例模式(eg:连接池)
用单例模式创建连接池:
class CP:
    __instance = None
    def __init__(self):
        self.ip = "1.1.1.1"
        self.port = 3306
        self.pwd = "123123"
        self.user = "xxx"
        self.conn_list = [1,2,3,4,5,6]
    @staticmethod
    def get_instance():
        if CP.__instance:
            return CP.__instance
        else:
            # 创建一个对象,并将对象赋值给静态字段__instance
            CP.__instance = CP() #执行init方且创建对象,并赋值给私有静态字段
            return CP.__instance #将赋值的返回给私有静态字段

obj1 = CP.get_instance() # 静态字段类调用
print(obj1)

 方法二:

class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)#orig是object
            cls._instance = orig.__new__(cls, *args, **kw) #使用的是object的new方法
        return cls._instance

class MyClass(Singleton):
    a = 1

推荐书籍:大话设计模式


原文地址:https://www.cnblogs.com/renfanzi/p/5827730.html