Example 1. Single Mode:
a. the use of import
#a.py class Animal(object): def __init__(self,name,coler): self.name = name self.coler = coler def run(self): print('{} {} can run!'.format(self.coler,self.name)) animal = Animal('dog','white')
# b.py from a import animal animal.run()
The module is a natural python singleton
b. Using the decorator
def Singleton(cls): _instance = {} def wrapper(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return wrapper @Singleton class A(object): def __init__(self, a): self.a = a a = A('sss') print(id(a)) print a.a b = A('fffff') print b.a # output: 44971888 sss 44971888 sss
The above method enables a single decorator embodiment, when A is first instantiated as a, when self.a = 'sss', the next b = A ( 'fffff'), Class A decorator has been determined examples, examples will directly return a, case b = a, is not instantiated, instead of referring to the assignment, so a, b and examples are the same self.a
c. Rewrite Method __new__
Import Threading class B (Object): Lock = of threading.Lock () # multithreaded cause in order to prevent a plurality of instances, the need to use thread-locking _instance = None DEF the __init__ (Self): self.b, = {} DEF __new__ is (CLS, args *, ** kwargs): IF not B._instance: # If no instance of the class with B.lock: # thread locking IF not B._instance: # again to determine whether there is an example (probably the first to create an instance of other threads) B ._instance = Object. __new__ (CLS) # create an instance of return B._instance # If there is already an example, direct returns an instance def push(self): self.b = {'1': 1} b1 = B() print(id(b1)) b1.push() print b1.b b2 = B() print id(b2) print b2.b # output: 44409392 {'1': 1} 44409392 {}
This method has a problem, the push method performed b1 instance, slef.b = { '1': 1}
However, after b2 instantiated self.b = {}, understand? __init__ is performed again
d. metaclass implemented
class SingletonType(type): def __init__(self, *args, **kwargs): super(SingletonType, self).__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类 print('cls', cls) obj = cls.__new__(cls, *args, **kwargs) cls.__init__(obj, *args, **kwargs) # Foo.__init__(obj) return obj metaclass = SingletonType class Foo(): # 指定创建Foo的type为SingletonType def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): return object.__new__(cls) obj1 = Foo('xx') print(id(obj1)) print(obj1.name) obj2 = Foo('xxx') print(id(obj2)) print(obj2.name) # output: 43996104 xx 43996144 xxx
2. abstract factory pattern
# -*- coding:utf-8 -*- import abc import six class Phone(object): def installer_cpu(self): pass class Notebook(object): def installer_cpu(self): pass class XiaomiPhone(Phone): def installer_cpu(self): print('骁龙855') class HuaweiPhone(Phone): def installer_cpu(self): print('麒麟980') class XiaomiNotebook(Notebook): def installer_cpu(self): print('intel i7-8550u') class HuaweiNotebook(Notebook): def installer_cpu(self): print('intel i5-8265u') @six.add_metaclass(abc.ABCMeta) class Factory(object): """ 抽象工厂类 """ @abc.abstractmethod def production_phone(self): pass @abc.abstractmethod def production_notebook(self): pass class XiaomiFactory(Factory): """ Millet production plant "" " DEF production_phone (Self): return XiaomiPhone () DEF production_notebook (Self): return XiaomiNotebook () class HuaweiFactory (Factory's): " "" Huawei's production plant "" " DEF production_phone (Self): return HuaweiPhone () DEF production_notebook (Self): return HuaweiNotebook () DEF main (): # to a Huawei phones Huawei = HuaweiFactory () huawei_p30 = Huawei.production_phone () huawei_p30.installer_cpu() # To a millet phone Xiaomi = XiaomiFactory () xiaomi9 = Xiaomi.production_phone () xiaomi9.installer_cpu () # to be a huawei notebook Huawei = HuaweiFactory () huawei_matebook14 = Huawei.production_notebook () huawei_matebook14.installer_cpu () # to a millet notebook = Xiaomi XiaomiFactory () xiaomi_bookPro = Xiaomi.production_notebook () xiaomi_bookPro.installer_cpu () IF the __name__ == ' __main__ ' : main ()
# Output:
Kirin 980
Xiaolong 855
intel i5-8265u
intel i7-8550u