创建型模式
工厂模式
定义了一个用于创建对象的接口,让子类决定实例化哪一个类,使一个类的实例化延迟到其子类。
#鼠标基类 class Mouse: pass #戴尔鼠标类 class DellMouse(Mouse): pass #惠普鼠标类 class HpMouse(Mouse): pass #鼠标工厂类 class MouseFactory: def getMouse(self, name): if name == 'Dell': return DellMouse() elif name == 'Hp': return HpMouse() #实例化鼠标工厂 factory = MouseFactory() #生产戴尔鼠标 mouse = factory.getMouse('Dell')
抽象工厂模式
是一种为访问类提供一个创建一组相关或相互依赖对象的接口,且访问类无须指定所要产品的具体类就能得到同族的不同等级的产品的模式结构
#鼠标基类 class Mouse: pass #戴尔鼠标类 class DellMouse(Mouse): pass #惠普鼠标类 class HpMouse(Mouse): pass #键盘基类 class Keyboard: pass #戴尔键盘类 class DellKeyboard(Keyboard): pass #惠普键盘类 class HpKeyboard(Keyboard): pass #Dell工厂类 class DellFactory: def createMouse(self): return HpMouse() def createKeyborad(self): return HpKeyboard() #Hp工厂商类 class HpFactory: def createMouse(self): return HpMouse() def createKeyborad(self): return HpKeyboard() #PC厂商类 class PcFactory: def getFactory(self, name): if name == 'Dell': return DellFactory() elif name == 'Hp': return HpFactory() pcfactory = PcFactory() factory = pcfactory.getFactory('Dell') factory.createMouse()
单例模式
- 使用模块
模块在第一次导入时,会生成 .pyc
文件,当第二次导入时,就会直接加载 .pyc
文件,而不会再次执行模块代码
class GlobalCls(dict): pass g = GlobalCls()
- 使用装饰器
def singleton(cls): _instance = {} def _singleton(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, *kwargs) return _instance[cls] return _singleton @singleton class GlobalCls(dict): pass
In [2]: GlobalCls()['name'] = 'ply' In [3]: GlobalCls() Out[3]: {'name': 'ply'}
- 使用__new__方法
class GlobalCls(dict): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance
In [10]: GlobalCls()['name'] = 'ply' In [11]: GlobalCls() Out[11]: {}
单实例没生效,应该是继承导致的
class GlobalCls(): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance
In [35]: id(GlobalCls()) Out[35]: 1901732620048 In [36]: id(GlobalCls()) Out[36]: 1901732620048
小结:重写__new__方法实现单例不适合有继承的情况
-
使用metaclass
class SingletonType(type): def __call__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): cls._instance = super().__call__(*args, **kwargs) return cls._instance class GlobalCls(dict, metaclass=SingletonType): pass
In [56]: GlobalCls()['name'] = 'ply' In [57]: GlobalCls() Out[57]: {'name': 'ply'}