当前位置: 首页 > news >正文

澄海网站建设汕头微网站

澄海网站建设,汕头微网站,合肥seo公司,明年做啥网站能致富From#xff1a;http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html 一、简单工厂模式 模式特点#xff1a;工厂根据条件产生不同功能的类。 程序实例#xff1a;四则运算计算器#xff0c;根据用户的输入产生相应的运算类#xff0c;用这个运算类处理具…  Fromhttp://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html 一、简单工厂模式 模式特点工厂根据条件产生不同功能的类。 程序实例四则运算计算器根据用户的输入产生相应的运算类用这个运算类处理具体的运算。 代码特点C/C中的switch...case...分支使用字典的方式代替。      使用异常机制对除数为0的情况进行处理。 class Operation(object):def get_result(self):passclass Add(Operation):def get_result(self):return self.op1self.op2class Sub(Operation):def get_result(self):return self.op1 - self.op2class Mul(Operation):def get_result(self):return self.op1 * self.op2class Div(Operation):def get_result(self):return self.op1 / self.op2class Undef(Operation):def get_result(self):print no define operatorclass Factory(object):operator dict()operator[] Add()operator[-] Sub()operator[*] Mul()operator[/] Div()def create_operator(self, ch):op self.operator[ch] if ch in self.operator else Undef()return opdef main():print * * 30op raw_input(operator:)opa input(a:)opb input(b:)factory Factory()cal factory.create_operator(op)cal.op1 opa cal.op2 opbprint cal.get_result()if __name__ __main__:while 1:main()pass 二、策略模式 模式特点定义算法家族并且分别封装它们之间可以相互替换而不影响客户端。 程序实例商场收银软件需要根据不同的销售策略方式进行收费 代码特点不同于同例1这里使用字典是为了避免关键字不在字典导致bug的陷阱。 # _*_ coding:utf-8 _*_import osclass CashSuper(object):def accept_cash(self, money):return 0class CashNormal(CashSuper):def accept_cash(self, money):return moneyclass CashRebate(CashSuper):discount 0def __init__(self, ds):self.discount dsdef accept_cash(self, money):return money * self.discountclass CashReturn(CashSuper):total 0ret 0def __init__(self, total, ret):self.total totalself.ret retdef accept_cash(self, money):if money self.total:return money - self.retelse:return moneyclass CashContext:def __init__(self, child_class):self.cs child_classdef get_result(self, money):return self.cs.accept_cash(money)def main():print * * 30money input(money:)strategy dict()strategy[1] CashContext(CashNormal())strategy[2] CashContext(CashRebate(0.8))strategy[3] CashContext(CashReturn(300, 100))ctype input(type:[1]for normal,[2]for 80% discount [3]for 300 -100.)if ctype in strategy:cc strategy[ctype]else:print no define type. Use normal mode.cc strategy[1]print you will pay:%d % (cc.GetResult(money))if __name__ __main__:main()三、装饰模式 模式特点动态地为对象增加额外的职责 程序实例展示一个人一件一件穿衣服的过程。 代码特点无 class Person(object):def __init__(self, name):self.name namedef show(self):print dressed %s % self.nameclass Finery(Person):component Nonedef __init__(self):super(Finery, self).__init__()passdef decorate(self, ct):self.component ctdef show(self):if self.component is not None:self.component.show()class TShirts(Finery):def __init__(self):super(TShirts, self).__init__()passdef show(self):print Big T-shirt self.component.show()class BigTrouser(Finery):def __init__(self):super(BigTrouser, self).__init__()passdef show(self):print Big Trouser self.component.show()def main():p Person(somebody)bt BigTrouser()ts TShirts()bt.decorate(p)ts.decorate(bt)ts.show()if __name__ __main__:main()四、代理模式 模式特点为其他对象提供一种代理以控制对这个对象的访问。 程序实例同模式特点描述。 代码特点无 class Interface(object):def request(self):return 0class RealSubject(Interface):def request(self):print Real request.class Proxy(Interface):def request(self):self.real RealSubject()self.real.request()def main():p Proxy()p.request()if __name__ __main__:main() 五、工厂方法模式 模式特点定义一个用于创建对象的接口让子类决定实例化哪一个类。这使得一个类的实例化延迟到其子类。 程序实例基类雷锋类派生出学生类和志愿者类由这两种子类完成“学雷锋”工作。子类的创建由雷锋工厂的对应的子类完成。 代码特点无 class LeiFeng(object):def Sweep(self):print LeiFeng sweepclass Student(LeiFeng):def Sweep(self):print Student sweepclass Volenter(LeiFeng):def Sweep(self):print Volenter sweepclass LeiFengFactory:def CreateLeiFeng(self):temp LeiFeng()return tempclass StudentFactory(LeiFengFactory):def CreateLeiFeng(self):temp Student()return tempclass VolenterFactory(LeiFengFactory):def CreateLeiFeng(self):temp Volenter()return tempdef main():sf StudentFactory()s sf.CreateLeiFeng()s.Sweep()sdf VolenterFactory()sd sdf.CreateLeiFeng()sd.Sweep()if __name__ __main__:main() 六、原型模式 模式特点用原型实例指定创建对象的种类并且通过拷贝这些原型创建新的对象。 程序实例从简历原型生成新的简历 代码特点简历类Resume提供的Clone()方法其实并不是真正的Clone只是为已存在对象增加了一次引用。 Python为对象提供的copy模块中的copy方法和deepcopy方法已经实现了原型模式但由于例子的层次较浅二者看不出区别。 import copy class WorkExp:placeyear0class Resume:name age 0def __init__(self,n):self.name ndef SetAge(self,a):self.age adef SetWorkExp(self,p,y):self.place pself.year ydef Display(self):print self.ageprint self.placeprint self.yeardef Clone(self):#实际不是“克隆”只是返回了自身return selfdef main():a Resume(a)b a.Clone()c copy.copy(a)d copy.deepcopy(a)a.SetAge(7)b.SetAge(12)c.SetAge(15)d.SetAge(18)a.SetWorkExp(PrimarySchool, 1996)b.SetWorkExp(MidSchool, 2001)c.SetWorkExp(HighSchool, 2004)d.SetWorkExp(University, 2007)a.Display()b.Display()c.Display()d.Display()if __name__ __main__:main()七、模板方法模式 模式特点定义一个操作中的算法骨架将一些步骤延迟至子类中。 程序实例考试时使用同一种考卷父类不同学生上交自己填写的试卷子类方法的实现 代码特点无 模板方法模式class TestPaper:def TestQuestion1(self):print Test1:A. B. C. D.print (%s) %self.Answer1()def TestQuestion2(self):print Test1:A. B. C. D.print (%s) %self.Answer2()def Answer1(self):return def Answer2(self):return class TestPaperA(TestPaper):def Answer1(self):return Bdef Answer2(self):return C;class TestPaperB(TestPaper):def Answer1(self):return Ddef Answer2(self):return D;if __name__ __main__:s1 TestPaperA()s2 TestPaperB()print student 1s1.TestQuestion1()s1.TestQuestion2()print student 2s2.TestQuestion1()s2.TestQuestion2() 八、外观模式 模式特点为一组调用提供一致的接口。 程序实例接口将几种调用分别组合成为两组用户通过接口调用其中的一组。 代码特点无 外观模式class SubSystemOne:def MethodOne(self):print SubSysOneclass SubSystemTwo:def MethodTwo(self):print SubSysTwoclass SubSystemThree:def MethodThree(self):print SubSysThreeclass SubSystemFour:def MethodFour(self):print SubSysFourclass Facade:def __init__(self):self.one SubSystemOne()self.two SubSystemTwo()self.three SubSystemThree()self.four SubSystemFour()def MethodA(self):print MethodAself.one.MethodOne()self.two.MethodTwo()self.four.MethodFour()def MethodB(self):print MethodBself.two.MethodTwo()self.three.MethodThree()if __name__ __main__:facade Facade()facade.MethodA()facade.MethodB() 九、建造者模式 模式特点将一个复杂对象的构建(Director)与它的表示(Builder)分离使得同样的构建过程可以创建不同的表示(ConcreteBuilder)。 程序实例“画”出一个四肢健全头身手腿的小人 代码特点无 建造者模式class Person:def CreateHead(self):passdef CreateHand(self):passdef CreateBody(self):passdef CreateFoot(self):passclass ThinPerson(Person):def CreateHead(self):print thin headdef CreateHand(self):print thin handdef CreateBody(self):print thin bodydef CreateFoot(self):print thin footclass ThickPerson(Person):def CreateHead(self):print thick headdef CreateHand(self):print thick handdef CreateBody(self):print thick bodydef CreateFoot(self):print thick footclass Director:def __init__(self,temp):self.p tempdef Create(self):self.p.CreateHead()self.p.CreateBody()self.p.CreateHand()self.p.CreateFoot()if __name__ __main__:p ThickPerson()d Director(p)d.Create() 十、观察者模式 模式特点定义了一种一对多的关系让多个观察对象同时监听一个主题对象当主题对象状态发生变化时会通知所有观察者。 程序实例公司里有两种上班时趁老板不在时偷懒的员工看NBA的和看股票行情的并且事先让老板秘书当老板出现时通知他们继续做手头上的工作。 程序特点无 观察者模式class Observer:def __init__(self,strname,strsub):self.name strnameself.sub strsubdef Update(self):passclass StockObserver(Observer):#no need to rewrite __init__()def Update(self):print %s:%s,stop watching Stock and go on work! %(self.name,self.sub.action)class NBAObserver(Observer):def Update(self):print %s:%s,stop watching NBA and go on work! %(self.name,self.sub.action)class SecretaryBase:def __init__(self):self.observers []def Attach(self,new_observer):pass def Notify(self):passclass Secretary(SecretaryBase):def Attach(self,new_observer):self.observers.append(new_observer)def Notify(self):for p in self.observers:p.Update()if __name__ __main__:p Secretary()s1 StockObserver(xh,p)s2 NBAObserver(wyt,p)p.Attach(s1);p.Attach(s2);p.action WARNING:BOSS ;p.Notify() 十一、抽象工厂模式 模式特点提供一个创建一系列相关或相互依赖对象的接口而无需指定它们的类。 程序实例提供对不同的数据库访问的支持。 IUser和IDepartment是两种不同的抽象产品它们都有Access和SQL Server这两种不同的实现IFactory是产生IUser和IDepartment的抽象工厂根据具体实现AccessFactory和SqlFactory产生对应的具体的对象CAccessUser与CAccessDepartment或者CSqlUser与CSqlDepartment。 代码特点无 抽象工厂模式class IUser:def GetUser(self):passdef InsertUser(self):passclass IDepartment:def GetDepartment(self):passdef InsertDepartment(self):passclass CAccessUser(IUser):def GetUser(self):print Access GetUserdef InsertUser(self):print Access InsertUserclass CAccessDepartment(IDepartment):def GetDepartment(self):print Access GetDepartmentdef InsertDepartment(self):print Access InsertDepartmentclass CSqlUser(IUser):def GetUser(self):print Sql GetUserdef InsertUser(self):print Sql InsertUserclass CSqlDepartment(IDepartment):def GetDepartment(self):print Sql GetDepartmentdef InsertDepartment(self):print Sql InsertDepartmentclass IFactory:def CreateUser(self):passdef CreateDepartment(self):passclass AccessFactory(IFactory):def CreateUser(self):tempCAccessUser()return tempdef CreateDepartment(self):temp CAccessDepartment()return tempclass SqlFactory(IFactory):def CreateUser(self):temp CSqlUser()return tempdef CreateDepartment(self):temp CSqlDepartment()return tempif __name__ __main__:factory SqlFactory()userfactory.CreateUser()departfactory.CreateDepartment()user.GetUser()depart.GetDepartment() 十二、状态模式 模式特点当一个对象的内在状态改变时允许改变其行为这个对象看起来像是改变了其类。 程序实例描述一个程序员的工作状态当需要改变状态时发生改变不同状态下的方法实现不同 代码特点无 状态模式class State:def WirteProgram(self):passclass Work:def __init__(self):self.hour 9self.current ForenoonState()def SetState(self,temp):self.current tempdef WriteProgram(self):self.current.WriteProgram(self)class NoonState(State):def WriteProgram(self,w):print noon workingif (w.hour13):print fun.else:print need to rest.class ForenoonState(State):def WriteProgram(self,w):if (w.hour12):print morning workingprint energeticelse:w.SetState(NoonState()) w.WriteProgram()if __name__ __main__:mywork Work()mywork.hour 9mywork.WriteProgram()mywork.hour 14mywork.WriteProgram() 十三、适配器模式 模式特点将一个类的接口转换成为客户希望的另外一个接口。 程序实例用户通过适配器使用一个类的方法。 代码特点无 适配器模式class Target:def Request():print common request.class Adaptee(Target):def SpecificRequest(self):print specific request.class Adapter(Target):def __init__(self,ada):self.adaptee adadef Request(self):self.adaptee.SpecificRequest()if __name__ __main__:adaptee Adaptee()adapter Adapter(adaptee)adapter.Request() 十四、备忘录模式 模式特点在不破坏封装性的前提下捕获一个对象的内部状态并在该对象之外保存这个状态以后可以将对象恢复到这个状态。 程序实例将Originator对象的状态封装成Memo对象保存在Caretaker内 代码特点无 备忘录模式class Originator:def __init__(self):self.state def Show(self):print self.statedef CreateMemo(self):return Memo(self.state)def SetMemo(self,memo):self.state memo.stateclass Memo:state def __init__(self,ts):self.state tsclass Caretaker:memo if __name__ __main__:on Originator()on.state onon.Show()c Caretaker()c.memoon.CreateMemo()on.stateoffon.Show()on.SetMemo(c.memo)on.Show() 十五、组合模式 模式特点将对象组合成成树形结构以表示“部分-整体”的层次结构 程序实例公司人员的组织结构 代码特点无 组合模式class Component:def __init__(self,strName):self.m_strName strNamedef Add(self,com):passdef Display(self,nDepth):passclass Leaf(Component):def Add(self,com):print leaf cant adddef Display(self,nDepth):strtemp for i in range(nDepth):strtempstrtemp-strtempstrtempself.m_strNameprint strtempclass Composite(Component):def __init__(self,strName):self.m_strName strNameself.c []def Add(self,com):self.c.append(com)def Display(self,nDepth):strtempfor i in range(nDepth):strtempstrtemp-strtempstrtempself.m_strNameprint strtempfor com in self.c:com.Display(nDepth2)if __name__ __main__:p Composite(Wong)p.Add(Leaf(Lee))p.Add(Leaf(Zhao))p1 Composite(Wu)p1.Add(Leaf(San))p.Add(p1)p.Display(1); 十六、迭代器模式 模式特点提供方法顺序访问一个聚合对象中各元素而又不暴露该对象的内部表示 说明这个模式没有写代码实现原因是使用Python的列表和for ... in list就能够完成不同类型对象聚合的迭代功能了。 十七、单例模式 模式特点保证类仅有一个实例并提供一个访问它的全局访问点。 说明     为了实现单例模式费了不少工夫后来查到一篇博文对此有很详细的介绍而且实现方式也很丰富通过对代码的学习可以了解更多Python的用法。以下的代码出自GhostFromHeaven的专栏地址http://blog.csdn.net/ghostfromheaven/article/details/7671853。不过正如其作者在Python单例模式终极版所说 我要问的是Python真的需要单例模式吗我指像其他编程语言中的单例模式。 答案是不需要 因为Python有模块module最pythonic的单例典范。 模块在在一个应用程序中只有一份它本身就是单例的将你所需要的属性和方法直接暴露在模块中变成模块的全局变量和方法即可 单例模式四种方法#-*- encodingutf-8 -*- print ----------------------方法1-------------------------- #方法1,实现__new__方法 #并在将一个类的实例绑定到类变量_instance上, #如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回 #如果cls._instance不为None,直接返回cls._instance class Singleton(object):def __new__(cls, *args, **kw):if not hasattr(cls, _instance):orig super(Singleton, cls)cls._instance orig.__new__(cls, *args, **kw)return cls._instanceclass MyClass(Singleton):a 1one MyClass() two MyClass()two.a 3 print one.a #3 #one和two完全相同,可以用id(), , is检测 print id(one) #29097904 print id(two) #29097904 print one two #True print one is two #Trueprint ----------------------方法2-------------------------- #方法2,共享属性;所谓单例就是所有引用(实例、对象)拥有相同的状态(属性)和行为(方法) #同一个类的所有实例天然拥有相同的行为(方法), #只需要保证同一个类的所有实例具有相同的状态(属性)即可 #所有实例共享属性的最简单最直接的方法就是__dict__属性指向(引用)同一个字典(dict) #可参看:http://code.activestate.com/recipes/66531/ class Borg(object):_state {}def __new__(cls, *args, **kw):ob super(Borg, cls).__new__(cls, *args, **kw)ob.__dict__ cls._statereturn obclass MyClass2(Borg):a 1one MyClass2() two MyClass2()#one和two是两个不同的对象,id, , is对比结果可看出 two.a 3 print one.a #3 print id(one) #28873680 print id(two) #28873712 print one two #False print one is two #False #但是one和two具有相同的同一个__dict__属性,见: print id(one.__dict__) #30104000 print id(two.__dict__) #30104000print ----------------------方法3-------------------------- #方法3:本质上是方法1的升级或者说高级版 #使用__metaclass__元类的高级python用法 class Singleton2(type):def __init__(cls, name, bases, dict):super(Singleton2, cls).__init__(name, bases, dict)cls._instance Nonedef __call__(cls, *args, **kw):if cls._instance is None:cls._instance super(Singleton2, cls).__call__(*args, **kw)return cls._instanceclass MyClass3(object):__metaclass__ Singleton2one MyClass3() two MyClass3()two.a 3 print one.a #3 print id(one) #31495472 print id(two) #31495472 print one two #True print one is two #Trueprint ----------------------方法4-------------------------- #方法4:也是方法1的升级高级版本, #使用装饰器(decorator), #这是一种更pythonic,更elegant的方法, #单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的 def singleton(cls, *args, **kw):instances {}def _singleton():if cls not in instances:instances[cls] cls(*args, **kw)return instances[cls]return _singletonsingleton class MyClass4(object):a 1def __init__(self, x0):self.x xone MyClass4() two MyClass4()two.a 3 print one.a #3 print id(one) #29660784 print id(two) #29660784 print one two #True print one is two #True one.x 1 print one.x #1 print two.x #1 十八、桥接模式 模式特点将抽象部分与它的实现部分分离使它们都可以独立地变化。 程序实例两种品牌的手机要求它们都可以运行游戏和通讯录两个软件而不是为每个品牌的手机都独立编写不同的软件。 代码特点虽然使用了object的新型类不过在这里不是必须的是对在Python2.2之后“尽量使用新型类”的建议的遵从示范。 桥接模式class HandsetSoft(object):def Run(self):passclass HandsetGame(HandsetSoft):def Run(self):print Gameclass HandsetAddressList(HandsetSoft):def Run(self):print Address Listclass HandsetBrand(object):def __init__(self):self.m_soft Nonedef SetHandsetSoft(self,temp):self.m_soft tempdef Run(self):passclass HandsetBrandM(HandsetBrand):def Run(self):if not (self.m_soft None):print BrandMself.m_soft.Run()class HandsetBrandN(HandsetBrand):def Run(self):if not (self.m_soft None):print BrandNself.m_soft.Run()if __name__ __main__:brand HandsetBrandM()brand.SetHandsetSoft(HandsetGame())brand.Run()brand.SetHandsetSoft(HandsetAddressList())brand.Run() 十九、命令模式 模式特点将请求封装成对象从而使可用不同的请求对客户进行参数化对请求排队或记录请求日志以及支持可撤消的操作。 程序实例烧烤店有两种食物羊肉串和鸡翅。客户向服务员点单服务员将点好的单告诉大厨由大厨进行烹饪。 代码特点注意在遍历列表时不要用注释的方式删除否则会出现bug。bug示例程序附在后面我认为这是因为remove打乱了for迭代查询列表的顺序导致的。 命令模式class Barbucer:def MakeMutton(self):print Muttondef MakeChickenWing(self):print Chicken Wingclass Command:def __init__(self,temp):self.receivertempdef ExecuteCmd(self):passclass BakeMuttonCmd(Command):def ExecuteCmd(self):self.receiver.MakeMutton()class ChickenWingCmd(Command):def ExecuteCmd(self):self.receiver.MakeChickenWing()class Waiter:def __init__(self):self.order []def SetCmd(self,command):self.order.append(command)print Add Orderdef Notify(self):for cmd in self.order:#self.order.remove(cmd)#lead to a bugcmd.ExecuteCmd()if __name__ __main__:barbucerBarbucer()cmdBakeMuttonCmd(barbucer)cmd2ChickenWingCmd(barbucer)girlWaiter()girl.SetCmd(cmd)girl.SetCmd(cmd2)girl.Notify() 在for中remove会导致bug的展示代码 bugc[0,1,2,3] for i in c:print ic.remove(i)#output: #0 #2 二十、职责链模式 模式特点使多个对象都有机会处理请求从而避免发送者和接收者的耦合关系。将对象连成链并沿着这条链传递请求直到被处理。 程序实例请假和加薪等请求发给上级如果上级无权决定那么递交给上级的上级。 代码特点无 职责链模式class Request:def __init__(self,tcontent,tnum):self.content tcontentself.num tnumclass Manager:def __init__(self,temp):self.name tempdef SetSuccessor(self,temp):self.manager tempdef GetRequest(self,req):passclass CommonManager(Manager):def GetRequest(self,req):if(req.num0 and req.num10):print %s handled %d request. %(self.name,req.num)else:self.manager.GetRequest(req)class MajorDomo(Manager):def GetRequest(self,req):if(req.num10):print %s handled %d request. %(self.name,req.num)if __name__ __main__:common CommonManager(Zhang)major MajorDomo(Lee)common.SetSuccessor(major)req Request(rest,33)common.GetRequest(req)req2 Request(salary,3)common.GetRequest(req2) 二十一、中介者模式 模式特点用一个对象来封装一系列的对象交互中介者使各对象不需要显示地相互引用从而使耦合松散而且可以独立地改变它们之间的交互。 程序实例两个对象通过中介者相互通信 代码特点无 中介者模式class Mediator:def Send(self,message,col):passclass Colleague:def __init__(self,temp):self.mediator tempclass Colleague1(Colleague):def Send(self,message):self.mediator.Send(message,self)def Notify(self,message):print Colleague1 get a message:%s %messageclass Colleague2(Colleague):def Send(self,message):self.mediator.Send(message,self)def Notify(self,message):print Colleague2 get a message:%s %messageclass ConcreteMediator(Mediator):def Send(self,message,col):if(colcol1):col2.Notify(message)else:col1.Notify(message)if __name__ __main__:m ConcreteMediator()col1 Colleague1(m)col2 Colleague1(m)m.col1col1m.col2col2col1.Send(How are you?);col2.Send(Fine.); 二十二、享元模式 模式特点运用共享技术有效地支持大量细粒度的对象。 程序实例一个网站工厂根据用户请求的类别返回相应类别的网站。如果这种类别的网站已经在服务器上那么返回这种网站并加上不同用户的独特的数据如果没有那么生成一个。 代码特点为了展示每种网站的由用户请求的次数这里为它们建立了一个引用次数的字典。 之所以不用Python的sys模块中的sys.getrefcount()方法统计引用计数是因为有的对象可能在别处被隐式的引用从而增加了引用计数。  享元模式import sysclass WebSite:def Use(self):passclass ConcreteWebSite(WebSite):def __init__(self,strName):self.name strNamedef Use(self,user):print Website type:%s,user:%s %(self.name,user)class UnShareWebSite(WebSite):def __init__(self,strName):self.name strNamedef Use(self,user):print UnShare Website type:%s,user:%s %(self.name, user)class WebFactory:def __init__(self):test ConcreteWebSite(test)self.webtype {test:test}self.count {test:0}def GetWeb(self,webtype):if webtype not in self.webtype:temp ConcreteWebSite(webtype)self.webtype[webtype] tempself.count[webtype] 1else:temp self.webtype[webtype]self.count[webtype] self.count[webtype]1return tempdef GetCount(self):for key in self.webtype:#print type: %s, count:%d %(key,sys.getrefcount(self.webtype[key]))print type: %s, count:%d %(key,self.count[key])if __name__ __main__:f WebFactory()wsf.GetWeb(blog)ws.Use(Lee)ws2f.GetWeb(show)ws2.Use(Jack)ws3f.GetWeb(blog)ws3.Use(Chen)ws4UnShareWebSite(TEST)ws4.Use(Mr.Q)print f.webtypef.GetCount() 二十三、解释器模式 模式特点给定一个语言定义它的文法的一种表示并定义一个解释器这个解释器使用该表示来解释语言中的句子。 程序实例只是模式特点的最简单示范 代码特点无 解释器模式class Context:def __init__(self):self.inputself.outputclass AbstractExpression:def Interpret(self,context):passclass Expression(AbstractExpression):def Interpret(self,context):print terminal interpretclass NonterminalExpression(AbstractExpression):def Interpret(self,context):print Nonterminal interpretif __name__ __main__:context c []c c [Expression()]c c [NonterminalExpression()]c c [Expression()]c c [Expression()]for a in c:a.Interpret(context) 二十四、访问者模式 模式特点表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。 程序实例对于男人和女人接受访问者的元素ObjectStructure用于穷举这些元素不同的遭遇具体的访问者引发两种对象的不同行为。 代码特点无 访问者模式# -*- coding: UTF-8 -*- class Person:def Accept(self,visitor):passclass Man(Person):def Accept(self,visitor):visitor.GetManConclusion(self)class Woman(Person):def Accept(self,visitor):visitor.GetWomanConclusion(self)class Action:def GetManConclusion(self,concreteElementA):passdef GetWomanConclusion(self,concreteElementB):passclass Success(Action):def GetManConclusion(self,concreteElementA):print 男人成功时背后有个伟大的女人def GetWomanConclusion(self,concreteElementB):print 女人成功时背后有个不成功的男人class Failure(Action):def GetManConclusion(self,concreteElementA):print 男人失败时闷头喝酒谁也不用劝def GetWomanConclusion(self,concreteElementB):print 女人失败时眼泪汪汪谁也劝不了class ObjectStructure:def __init__(self):self.plist[]def Add(self,p):self.plistself.plist[p]def Display(self,act):for p in self.plist:p.Accept(act)if __name__ __main__:os ObjectStructure()os.Add(Man())os.Add(Woman())sc Success()os.Display(sc)fl Failure()os.Display(fl)
http://www.sadfv.cn/news/141336/

相关文章:

  • 营销网站的功能构成域名备案后怎样做网站
  • 淮北建设网站网站批量查询
  • 销售网站免费模板闵行专业做网站
  • 建设网站是几个步骤百度一下app下载安装
  • 南宁百度网站推广网站构成三要素
  • 福建工程建设中心网站wordpress搜索修改
  • 北京网站推广服务注册公司名称大全免费
  • 做棋牌辅助网站肇庆建网站
  • 网站有没有做301新浪的网络营销方式
  • 北京有哪些网站公司网站开发语言php5.1
  • 询盘网站中国建设银行网站
  • 网站建设邀约话术阿里云lnmp安装wordpress
  • 自学php做网站用asp做的网站有哪些
  • 网站备案需要资料电子商务网站后台需求
  • 企业网站源码git电子商务网站建设期末试题08答案
  • 做网站需要提供什么资料宿州科技网站建设
  • 黄页网络的推广网站有哪些网做英文网站
  • 高唐做网站建设公司3d游戏制作软件
  • 网站建设维护去哪里学制作北京的名片
  • 南京专业网站制作哪家好汕头seo全网营销
  • 网站制作完成之后进入了什么阶段网络营销案例分析题及答案
  • 企业如何做好网站的seo优化响应式网站适合优化吗
  • 做的网站底部应该标注什么织梦cms怎么安装
  • 深圳网站网站建设杭州手机网站制作
  • 全国网站建设有实力wordpress pdf下载插件
  • 阿里巴巴免费做网站百度收录查询入口
  • 找人做jsp网站深圳建设交易网站
  • 用什么来网站开发好极简app制作器
  • 书香气的域名做网站邯郸建设局网站资质申报
  • 火车票网站建设工程咨询公司