1.使用类的绑定方法实现单例模式
class MySQL():
__instance = None
def __init__(self, ip, port):
self.info = (ip, port)
@classmethod
def singleton(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
cls.__instance.__init__('200', 9090)
return cls.__instance
else:
return cls.__instance
obj1 = MySQL.singleton()
obj2 = MySQL.singleton()
print(obj2 is obj1) # True
obj3 = MySQL(224, 454)
print(obj1, obj2, obj3)
2.使用自定义元类实现单例模式
class Mymeta(type):
__instance = None
def __init__(self, class_name, class_bases, class_dic):
self.__instance = object.__new__(self)
self.__init__(self.__instance, '127', 9080)
def __call__(self, *args, **kwargs):
if args or kwargs:
obj = object.__new__(self)
obj.__init__(*args, **kwargs)
return obj
else:
return self.__instance
class MySQL(object, metaclass=Mymeta):
def __init__(self, ip, port):
self.info = (ip, port)
obj1 = MySQL()
obj2 = MySQL()
print(obj2 is obj1)
obj3 = MySQL(224, 454)
print(obj1, obj2, obj3)
3.使用装饰器实现单例模式
def wrapper(func):
_instance = func('127', 8990)
def inner(*args, **kwargs):
if args or kwargs:
return func(*args, **kwargs)
else:
return _instance
return inner
@wrapper
class MySQL(object):
def __init__(self, ip, port):
self.info = (ip, port)
obj1 = MySQL()
obj2 = MySQL()
print(obj2 is obj1)
obj3 = MySQL(224, 454)
print(obj1, obj2, obj3)