工厂模式
‘工厂模式‘ class msg(object): def mail(self,msg): pass def sms(self,msg): pass def weixin(self,msg): pass def sender(self,msg,msg_type): if msg_type == ‘sms‘: self.sms(msg) elif msg_type == ‘mail‘: self.mail(msg)
单立模式
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = ‘gaogd‘ ‘‘‘ 单立模式 ‘‘‘ def singletion(cls): instances = {} def warpper(*args,**kwargs): if cls not in instances: instances[cls] = cls(*args,**kwargs) return instances[cls] return warpper @singletion class Myclass(object): def __init__(self,n): self.n = n c = Myclass(‘10‘) c2 = Myclass(‘20‘) ## 装饰器的作用: @singletion 《=》 Myclass = singletion(Myclass) # print ‘--->‘,c.n ,c2.n #方法2,实现__new__方法 #并在将一个类的实例绑定到类变量_instance上, #如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回 #如果cls._instance不为None,直接返回cls._instance class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, ‘_instance‘): ##如果cls中不包含_instance方法,就执行下面 orig = super(Singleton, cls) ##继承原始的类 cls._instance = orig.__new__(cls, *args, **kw) ##在这个类上面添加_instance方法 return cls._instance ##返回这个新类 class MyClass1(Singleton): a = 1 one = MyClass1() two = MyClass1() two.a = 5 print one.a,two.a ### __new__()方法负责生成__init__()方法的
时间: 2024-10-25 18:01:44