单例模式

class MySQL:
__sign = None
def __init__(self):
self.host = "127.0.0.1"
self.port = 3306

@classmethod
def signleton(cls):
if not cls.__sign:
obj = cls()
cls.__sign = obj
return cls.__sign

def conn(self):
pass

m1 = MySQL.signleton()
m2 = MySQL.signleton()
print(m1 is m2,"1")

#但是这样必须调用类方法sighlenton来实例化。

"""
通过元类实现单例模式
"""


class MySQLmeta(type):
__sign = None

def __call__(self, *args, **kwargs):
if not MySQLmeta.__sign:
obj = object.__new__(self)
self.__init__(obj, *args, **kwargs)
MySQLmeta.__sign = obj
return MySQLmeta.__sign


class MySQL(metaclass=MySQLmeta):
def __init__(self):
self.host = "127.0.0.1"
self.port = 3306

def conn(self):
pass

m1 = MySQL()
m2 = MySQL()
print(m1 is m2,"2")


class MySQLmeta(type):

def __init__(self, class_name, class_bases, class_dict):
super(MySQLmeta, self).__init__(class_name, class_bases, class_dict)
self.__sign = None

def __call__(self, *args, **kwargs):
if not self.__sign:
obj = object.__new__(self)
self.__init__(obj, *args, **kwargs)
self.__sign = obj
return self.__sign


class MySQL(metaclass=MySQLmeta):
def __init__(self):
self.host = "127.0.0.1"
self.port = 3306

def conn(self):
pass

m1 = MySQL()
m2 = MySQL()
print(m1 is m2,"3")

"""
通过new方法实现单例模式
"""

class MySQL(metaclass=MySQLmeta):
__sign = None

def __new__(cls, *args, **kwargs):
if not cls.__sign:
obj = super().__new__(cls, *args, **kwargs)
cls.__sign = obj
return cls.__sign

def __init__(self):
self.host = "127.0.0.1"
self.port = 3306

def conn(self):
pass

m1 = MySQL()
m2 = MySQL()
print(m1 is m2,"4")
posted @ 2019-04-26 18:33  walle_zhao  阅读(117)  评论(0编辑  收藏  举报