CSIC_716_20191129【 单例模式 的五种实现方式】

 单例模式

单例模式:在确定类中的属性和方法不变时,需要反复调用该类的情况。  让所有通过该类实例化出的对象,都指向同一个内存地址。

优点:节省内存空间。

单例模式有五种表现形式:

1.通过classmethod实现

2.通过装饰器实现

3.通过__new__实现

4.通过导入模块时实现

5.通过元类实现

'''
每次调用都会生成同一个实例化对象
'''


class MySQL:
    __currentobj = None

    def __init__(self, host, port):
        self.host = host
        self.port = port

    @classmethod
    def uniom(cls, host, port):
        if not cls.__currentobj:
            obj = cls(host, port)
            cls.__currentobj = obj
        return cls.__currentobj


print(MySQL.uniom('192.168.0.1', 9090))  # <__main__.MySQL object at 0x000001D70EF1F148>
print(MySQL.uniom('192.0.0.1', 8080))  # <__main__.MySQL object at 0x000001D70EF1F148>

  

猜你喜欢

转载自www.cnblogs.com/csic716/p/11958418.html