单例模式的几种实现方式:
1.使用模块
2.使用__new__
3.使用装饰器
4.使用元类
使用模块:python的模块就是天然的单例模式,因为模块在第一次导入的时候,会生成.pyc的文件,在第二次导入的时候就会直接加载.pyc文件,而不会再次执行模块代码
使用__new__:
# 实例化一个单例 class Singleton(object): __instance = None def __new__(cls, age, name): #如果类属性__instance的值为None, #那么就创建一个对象,并且赋值为这个对象的引用,保证下次调用这个方法时 #能够知道之前已经创建过对象了,这样就保证了只有1个对象 if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance a = Singleton(18, "dongGe") b = Singleton(8, "dongGe") print(id(a)) print(id(b))
使用装饰器:
from functools import wraps def singleton(cls): instances = {} @wraps(cls) def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances return getinstance @singleton class Bar: pass b0 = Bar() b1 = Bar() print(id(b0)) print(id(b1))
使用元类:
元类(metaclass)可以控制类的创建过程
class Singleton(type): """ 元类继承type """ _instance = {} def __call__(cls, *args, **kwargs): if cls not in cls._instance: cls._instance[cls] = super().__call__(*args, **kwargs) return cls._instance class Bar(metaclass=Singleton): pass b0 = Bar() b1 = Bar() print(id(b0)) print(id(b1))
工厂模式:
class Fruit(object): def __init__(self): pass def print_color(self): pass class Apple(Fruit): def __init__(self): pass def print_color(self): print("apple is in red") class Orange(Fruit): def __init__(self): pass def print_color(self): print("orange is in orange") class FruitFactory(object): fruits = {"apple":Apple,"orange":Orange} def __new__(cls, name): if name in cls.fruits.keys(): return cls.fruits[name]() else: return Fruit() fruit1 = FruitFactory("apple") fruit2 = FruitFactory("orange")