1. 装饰器函数实现单例设计模式
"""
实现思路:先将类传给cls,然后调用get_instance方法
"""
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Order:
def __init__(self, title, price):
self.title = title
self.price = price
def save(self):
print(f'保存订单{self.title}成功!')
@singleton
class OrderInfo:
def __init__(self, order_id, good_id):
self.order_id = order_id
self.goods_id = good_id
def save(self):
print(f'保存订单{self.order_id}的详情{self.goods_id}成功!')
def save(*args):
for obj in args:
obj.save()
if __name__ == '__main__':
o1 = Order('Phone7', 9000)
o2 = Order('Lenvon 9000', 4500)
oi1 = OrderInfo(1, '1110000')
oi2 = OrderInfo(1, '1130000')
save(o1, o2, oi1, oi2)
2. 基类方式实现单例设计
import json
import pickle
class Singleton:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls, *args, **kwargs)
cls._instance.sets = {}
return cls._instance
class SingletonHashSet(Singleton):
def add(self, key, value):
self.sets[key] = value
def exists(self, key):
return key in self.sets
def get(self, key):
if key not in self.sets:
raise KeyError(f'{key} not exisits')
return self.sets[key]
def remove(self, key):
if self.exists(key):
del self.sets[key]
def __str__(self):
return json.dumps(self.sets)
if __name__ == '__main__':
app = SingletonHashSet()
app.add('name', 'disen')
app.add('age', 20)
print(app)
app2 = SingletonHashSet()
app2.add('name2', 'jack')
app2.add('age2', 18)
print(app2)
3. 元类方式实现单例设计模式
"""
注意:
python2写法:
class Apple():
__metaclass__=Singleton
python3写法:
class Apple(metaclass=Singleton):
"""
class Singleton(type):
def __call__(cls, *args, **kwargs):
print(args)
print(kwargs)
if not hasattr(cls, '_instance'):
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class Apple(metaclass=Singleton):
def __init__(self, name):
self.name = name
if __name__ == '__main__':
a1 = Apple('jack')
a2 = Apple('mack')
print(a1.name, a2.name)
print(a1 is a2)
4-----继承
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls)
return cls._instance
class SqlClient(Singleton):
info = None
def register(self, host, user, passwd):
self.info = "{}--{}--{}".format(host, user, passwd)
继承父类的init,new魔术方法总结
- 只要相同子类继承同一个单例父类,其id 均相同
- init 魔术方法
1.父类名.__init__(self,*args,**kwargs)
2.super(子类名,self).__init__(*args,**kwargs)
3. 2的改动 super() 方法里头不用带参数
1.super(子类名,cls).__new__(cls《SEED》,*args,**kwargs)
去掉SEED,报错,typeError,super.__new__(子类名),子类名 is not a subtype of a super ?????????
eg.
cls._instance = super(Singleton).__new__(cls, *args, **kw)
单例的子类BUS
3.对1的改动 super() 方法里头不用带参数
2.父类名.__new__(cls)
cls._instance = super().__new__( 【cls,】*args, **kwargs)