工厂模式
'工厂模式' 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) import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" %format) return output_function(data)
单立模式
#!/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__()方法的
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。