实现单例模式的四种方法

实现单例模式的四种方法

单例模式定义:整个过程中只有一个实例,所有生成的实例都指向同一块内存空间

第一种:(类的绑定方法)

PORT = 3306
HOST = '127.0.0.1'

class Sql:
    instance = None
    def __init__(self,port,host):
        self.port = port
        self.host = host
    @classmethod
    def get_sigo(cls):
        if not cls.instance:
            cls.flag = cls(PORT,HOST)
        return cls.instance
    
#每次调用get_sigoleton 拿到的对象都是同一个
s1=Sql.get_si()
s2=Sql.get_si()
s3=Sql.get_si()
s4=Sql('33306','192.168.1.1')
print(s1)
print(s2)
print(s3)
print(s4)
'''
<__main__.Sql object at 0x02DF4030>
<__main__.Sql object at 0x02DF4030>
<__main__.Sql object at 0x02DF4030>
<__main__.Sql object at 0x02DF4190>
'''

第二种:(装饰器)

#当用户输入端口和地址,实例化产生新对象
#当用户不输入端口和地址,每次拿到的对象,都是同一个
PORT = 3306
HOST = '127.0.0.1'

def get_sigo(func):
    instance = None
    def wrapper(*args,**kwargs):
        if len(args) != 0 or len(kwargs) != 0:
            #表示传了参数,生成新对象
            res = func(*args,**kwargs)
            return res
        else:
            nonlocal instance
            if not instance:
                instance = func(PORT,HOST)
            return instance
    return wrapper

@get_sigo
class Sql:
    def __init__(self,port,host):
        self.port = port
        self.host = host

s1=Sql()
s2=Sql()
s3=Sql('33306','192.168.1.1')
s4=Sql('33306','192.168.1.1')
print(s1)
print(s2)
print(s3)
print(s4)
'''
<__main__.Sql object at 0x036A41B0>
<__main__.Sql object at 0x036A41B0>
<__main__.Sql object at 0x036A41D0>
<__main__.Sql object at 0x036A41F0>
'''

第三种:(元类)

PORT = 3306
HOST = '127.0.0.1'

class Mymeta(type):
    def __init__(self,name,bases,dic):
        # 把实例化好的对象,放到类的名称空间
        self.instance = self(PORT,HOST)
    def __call__(self,*args,**kwargs):
        if len(args) != 0 or len(kwargs) != 0:
            obj = object.__new__(self)
            obj.__init__(*args,**kwargs)
            return obj
        else:
            return self.instance
class Sql(metaclass = Mymeta):
    def __init__(self,port,host):
        self.port=port
        self.host=host
        
print(Sql.__dict__)
s1=Sql()
s2=Sql()
s3=Sql('33306','192.168.1.1')
print(s1)
print(s2)
print(s3)
'''
<__main__.Sql object at 0x034740D0>
<__main__.Sql object at 0x034740D0>
<__main__.Sql object at 0x03474050>
'''

第四种:(模块导入)

# sigo 文件
# ************************************
PORT = 3306
HOST = '127.0.0.1'
class Sql():
    def __init__(self,port,host):
        self.port=port
        self.host=host

s1=Sql(PORT,HOST)
# ************************************

def test():
    from sigo import s1
    print(s1)
def test2():
    from sigo import s1 as s2
    print(s2)

test()
test2()
from sigo import s1
from sigo import Sql
s2=Sql(3306,'192.168.1.1')
print(s1)
print(s2)

'''
<sigonleton.Sql object at 0x03A46AB0>
<sigonleton.Sql object at 0x03A46AB0>
<sigonleton.Sql object at 0x03A46AB0>
<sigonleton.Sql object at 0x03A22E30>
'''
posted @ 2019-09-04 22:08  SweetJack  阅读(211)  评论(0编辑  收藏  举报