![《大話設計模式》Python版代碼實現(xiàn)_第1頁](http://file2.renrendoc.com/fileroot_temp3/2021-4/24/1bd2654d-b848-41ab-babf-c2a799dde357/1bd2654d-b848-41ab-babf-c2a799dde3571.gif)
![《大話設計模式》Python版代碼實現(xiàn)_第2頁](http://file2.renrendoc.com/fileroot_temp3/2021-4/24/1bd2654d-b848-41ab-babf-c2a799dde357/1bd2654d-b848-41ab-babf-c2a799dde3572.gif)
![《大話設計模式》Python版代碼實現(xiàn)_第3頁](http://file2.renrendoc.com/fileroot_temp3/2021-4/24/1bd2654d-b848-41ab-babf-c2a799dde357/1bd2654d-b848-41ab-babf-c2a799dde3573.gif)
![《大話設計模式》Python版代碼實現(xiàn)_第4頁](http://file2.renrendoc.com/fileroot_temp3/2021-4/24/1bd2654d-b848-41ab-babf-c2a799dde357/1bd2654d-b848-41ab-babf-c2a799dde3574.gif)
![《大話設計模式》Python版代碼實現(xiàn)_第5頁](http://file2.renrendoc.com/fileroot_temp3/2021-4/24/1bd2654d-b848-41ab-babf-c2a799dde357/1bd2654d-b848-41ab-babf-c2a799dde3575.gif)
版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、大話設計模式Python版代碼實現(xiàn)上一周把大話設計模式看完了,對面向?qū)ο蠹夹g有了新的理解,對于一個在C下寫代碼比較多、偶爾會用到一些腳本語言寫腳本的人來說,很是開闊眼界。大話設計模式的代碼使用C#寫成的,而在本人接觸到的面向?qū)ο笳Z言中,只對C+和Python還算了解,為了加深對各個模式的理解,我在網(wǎng)上下載了一個C+版的源代碼,并根據(jù)自己的理解邊讀這本書邊動手實踐C+源代碼,同時將其改寫成了Python代碼,算是一箭三雕吧。由于這些代碼的目的是展示各個設計模式而非完成一個具體的復雜任務,基于C+版本改寫,例子的取材也和大話設計模式基本相同,再加上個人水平有限,因此這些Python版代碼寫的比較簡
2、單,雖然能跑起來是不假,不過難免有bug,而且實現(xiàn)也不一定最優(yōu),C+的味道比較濃而不夠pythonic,還請高手包容指正。不過我還是盡量把或多或少有些pythonic的東西放在每個模式的“代碼特點”部分進行展示,而這個“代碼特點”里也不僅僅是pythonic的東西。使用Python版本為2.6。配圖同樣摘自大話設計模式,因此是C#風格的UML類圖,為了便于排版已經(jīng)縮小了。一、簡單工廠模式模式特點:工廠根據(jù)條件產(chǎn)生不同功能的類。程序?qū)嵗核膭t運算計算器,根據(jù)用戶的輸入產(chǎn)生相應的運算類,用這個運算類處理具體的運算。代碼特點:C/C+中的switch.case.分支使用字典的方式代替。使用異常機制對
3、除數(shù)為0的情況進行處理。簡單工廠模式class Operation: def GetResult(self): passclass OperationAdd(Operation): def GetResult(self): return self.op1+self.op2class OperationSub(Operation): def GetResult(self): return self.op1-self.op2class OperationMul(Operation): def GetResult(self): return self.op1*self.op2class Operat
4、ionDiv(Operation): def GetResult(self): try: result = self.op1/self.op2 return result except: print error:divided by zero. return 0class OperationUndef(Operation): def GetResult(self): print Undefine operation. return 0class OperationFactory: operation = operation+ = OperationAdd(); operation- = Ope
5、rationSub(); operation* = OperationMul(); operation/ = OperationDiv(); def createOperation(self,ch): if ch in self.operation: op = self.operationch else: op = OperationUndef() return opif _name_ = _main_: op = raw_input(operator: ) opa = input(a: ) opb = input(b: ) factory = OperationFactory() cal =
6、 factory.createOperation(op) cal.op1 = opa cal.op2 = opb print cal.GetResult()二、策略模式模式特點:定義算法家族并且分別封裝,它們之間可以相互替換而不影響客戶端。程序?qū)嵗荷虉鍪浙y軟件,需要根據(jù)不同的銷售策略方式進行收費代碼特點:不同于同例1,這里使用字典是為了避免關鍵字不在字典導致bug的陷阱。策略模式class CashSuper: def AcceptCash(self,money): return 0class CashNormal(CashSuper): def AcceptCash(self,money)
7、: return moneyclass CashRebate(CashSuper): discount = 0 def _init_(self,ds): self.discount = ds def AcceptCash(self,money): return money * self.discountclass CashReturn(CashSuper): total = 0; ret = 0; def _init_(self,t,r): self.total = t self.ret = r def AcceptCash(self,money): if (money=self.total)
8、: return money - self.ret else: return moneyclass CashContext: def _init_(self,csuper): self.cs = csuper def GetResult(self,money): return self.cs.AcceptCash(money)if _name_ = _main_: money = input(money:) strategy = strategy1 = CashContext(CashNormal() strategy2 = CashContext(CashRebate(0.8) strate
9、gy3 = CashContext(CashReturn(300,100) ctype = input(type:1for normal,2for 80% discount 3for 300 -100.) if ctype in strategy: cc = strategyctype else: print Undefine type.Use normal mode. cc = strategy1 print you will pay:%d %(cc.GetResult(money)三、裝飾模式模式特點:動態(tài)地為對象增加額外的職責程序?qū)嵗赫故疽粋€人一件一件穿衣服的過程。代碼特點:無裝飾模式
10、class Person: def _init_(self,tname): = tname def Show(self): print dressed %s %()class Finery(Person): componet = None def _init_(self): pass def Decorate(self,ct): ponet = ct def Show(self): if(ponet!=None): ponet.Show()class TShirts(Finery): def _init_(s
11、elf): pass def Show(self): print Big T-shirt ponet.Show()class BigTrouser(Finery): def _init_(self): pass def Show(self): print Big Trouser ponet.Show()if _name_ = _main_: p = Person(somebody) bt = BigTrouser() ts = TShirts() bt.Decorate(p) ts.Decorate(bt) ts.Show()四、代理模式模式特點:為其他對象提供
12、一種代理以控制對這個對象的訪問。程序?qū)嵗和J教攸c描述。代碼特點:無代理模式class Interface : 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()if _name_ = _main_: p = Proxy() p.Request()五、工廠方法模式模式特點:定義一個
13、用于創(chuàng)建對象的接口,讓子類決定實例化哪一個類。這使得一個類的實例化延遲到其子類。程序?qū)嵗夯惱卒h類,派生出學生類和志愿者類,由這兩種子類完成“學雷鋒”工作。子類的創(chuàng)建由雷鋒工廠的對應的子類完成。代碼特點:無工廠方法模式class LeiFeng: def Sweep(self): print LeiFeng sweepclass Student(LeiFeng): def Sweep(self): print Student sweepclass Volenter(LeiFeng): def Sweep(self): print Volenter sweepclass LeiFengFact
14、ory: def CreateLeiFeng(self): temp = LeiFeng() return tempclass StudentFactory(LeiFengFactory): def CreateLeiFeng(self): temp = Student() return tempclass VolenterFactory(LeiFengFactory): def CreateLeiFeng(self): temp = Volenter() return tempif _name_ = _main_: sf = StudentFactory() s=sf.CreateLeiFe
15、ng() s.Sweep() sdf = VolenterFactory() sd=sdf.CreateLeiFeng() sd.Sweep()六、原型模式模式特點:用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象。程序?qū)嵗簭暮啔v原型,生成新的簡歷代碼特點:簡歷類Resume提供的Clone()方法其實并不是真正的Clone,只是為已存在對象增加了一次引用。Python為對象提供的copy模塊中的copy方法和deepcopy方法已經(jīng)實現(xiàn)了原型模式,但由于例子的層次較淺,二者看不出區(qū)別。原型模式import copyclass WorkExp: place= year=0cla
16、ss Resume: name = age = 0 def _init_(self,n): = n def SetAge(self,a): self.age = a def SetWorkExp(self,p,y): self.place = p self.year = y def Display(self): print self.age print self.place print self.year def Clone(self): #實際不是“克隆”,只是返回了自身 return selfif _name_ = _main_: a = Resume(a) b = a
17、.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()七、模板方法模式模式特點:定義一個操作中的算法骨架,將一些步驟延遲
18、至子類中。程序?qū)嵗嚎荚嚂r使用同一種考卷(父類),不同學生上交自己填寫的試卷(子類方法的實現(xiàn))代碼特點:無模板方法模式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(Tes
19、tPaper): def Answer1(self): return B def Answer2(self): return C;class TestPaperB(TestPaper): def Answer1(self): return D def Answer2(self): return D;if _name_ = _main_: s1 = TestPaperA() s2 = TestPaperB() print student 1 s1.TestQuestion1() s1.TestQuestion2() print student 2 s2.TestQuestion1() s2.Te
20、stQuestion2()八、外觀模式模式特點:為一組調(diào)用提供一致的接口。程序?qū)嵗航涌趯追N調(diào)用分別組合成為兩組,用戶通過接口調(diào)用其中的一組。代碼特點:無外觀模式class SubSystemOne: def MethodOne(self): print SubSysOneclass SubSystemTwo: def MethodTwo(self): print SubSysTwoclass SubSystemThree: def MethodThree(self): print SubSysThreeclass SubSystemFour: def MethodFour(self): p
21、rint SubSysFourclass Facade: def _init_(self): self.one = SubSystemOne() self.two = SubSystemTwo() self.three = SubSystemThree() self.four = SubSystemFour() def MethodA(self): print MethodA self.one.MethodOne() self.two.MethodTwo() self.four.MethodFour() def MethodB(self): print MethodB self.two.Met
22、hodTwo() self.three.MethodThree()if _name_ = _main_: facade = Facade() facade.MethodA() facade.MethodB()九、建造者模式模式特點:將一個復雜對象的構建(Director)與它的表示(Builder)分離,使得同樣的構建過程可以創(chuàng)建不同的表示(ConcreteBuilder)。程序?qū)嵗骸爱嫛背鲆粋€四肢健全(頭身手腿)的小人代碼特點:無建造者模式class Person: def CreateHead(self): pass def CreateHand(self): pass def Crea
23、teBody(self): pass def CreateFoot(self): passclass ThinPerson(Person): def CreateHead(self): print thin head def CreateHand(self): print thin hand def CreateBody(self): print thin body def CreateFoot(self): print thin footclass ThickPerson(Person): def CreateHead(self): print thick head def CreateHa
24、nd(self): print thick hand def CreateBody(self): print thick body def CreateFoot(self): print thick footclass Director: def _init_(self,temp): self.p = temp def Create(self): self.p.CreateHead() self.p.CreateBody() self.p.CreateHand() self.p.CreateFoot()if _name_ = _main_: p = ThickPerson() d = Dire
25、ctor(p) d.Create()十、觀察者模式模式特點:定義了一種一對多的關系,讓多個觀察對象同時監(jiān)聽一個主題對象,當主題對象狀態(tài)發(fā)生變化時會通知所有觀察者。程序?qū)嵗汗纠镉袃煞N上班時趁老板不在時偷懶的員工:看NBA的和看股票行情的,并且事先讓老板秘書當老板出現(xiàn)時通知他們繼續(xù)做手頭上的工作。程序特點:無觀察者模式class Observer: def _init_(self,strname,strsub): = strname self.sub = strsub def Update(self): passclass StockObserver(Observer):
26、#no need to rewrite _init_() def Update(self): print %s:%s,stop watching Stock and go on work! %(,self.sub.action)class NBAObserver(Observer): def Update(self): print %s:%s,stop watching NBA and go on work! %(,self.sub.action)class SecretaryBase: def _init_(self): self.observers =
27、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.Att
28、ach(s1); p.Attach(s2); p.action = WARNING:BOSS ; p.Notify()十一、抽象工廠模式模式特點:提供一個創(chuàng)建一系列相關或相互依賴對象的接口,而無需指定它們的類。程序?qū)嵗禾峁Σ煌臄?shù)據(jù)庫訪問的支持。IUser和IDepartment是兩種不同的抽象產(chǎn)品,它們都有Access和SQL Server這兩種不同的實現(xiàn);IFactory是產(chǎn)生IUser和IDepartment的抽象工廠,根據(jù)具體實現(xiàn)(AccessFactory和SqlFactory)產(chǎn)生對應的具體的對象(CAccessUser與CAccessDepartment,或者CSqlUser
29、與CSqlDepartment)。代碼特點:無抽象工廠模式class IUser: def GetUser(self): pass def InsertUser(self): passclass IDepartment: def GetDepartment(self): pass def InsertDepartment(self): passclass CAccessUser(IUser): def GetUser(self): print Access GetUser def InsertUser(self): print Access InsertUserclass CAccessDep
30、artment(IDepartment): def GetDepartment(self): print Access GetDepartment def InsertDepartment(self): print Access InsertDepartmentclass CSqlUser(IUser): def GetUser(self): print Sql GetUser def InsertUser(self): print Sql InsertUserclass CSqlDepartment(IDepartment): def GetDepartment(self): print S
31、ql GetDepartment def InsertDepartment(self): print Sql InsertDepartmentclass IFactory: def CreateUser(self): pass def CreateDepartment(self): passclass AccessFactory(IFactory): def CreateUser(self): temp=CAccessUser() return temp def CreateDepartment(self): temp = CAccessDepartment() return tempclas
32、s SqlFactory(IFactory): def CreateUser(self): temp = CSqlUser() return temp def CreateDepartment(self): temp = CSqlDepartment() return tempif _name_ = _main_: factory = SqlFactory() user=factory.CreateUser() depart=factory.CreateDepartment() user.GetUser() depart.GetDepartment()十二、狀態(tài)模式模式特點:當一個對象的內(nèi)在狀
33、態(tài)改變時允許改變其行為,這個對象看起來像是改變了其類。程序?qū)嵗好枋鲆粋€程序員的工作狀態(tài),當需要改變狀態(tài)時發(fā)生改變,不同狀態(tài)下的方法實現(xiàn)不同代碼特點:無狀態(tài)模式class State: def WirteProgram(self): passclass Work: def _init_(self): self.hour = 9 self.current = ForenoonState() def SetState(self,temp): self.current = temp def WriteProgram(self): self.current.WriteProgram(self)clas
34、s NoonState(State): def WriteProgram(self,w): print noon working if (w.hour13): print fun. else: print need to rest.class ForenoonState(State): def WriteProgram(self,w): if (w.hour12): print morning working print energetic else: w.SetState(NoonState() w.WriteProgram()if _name_ = _main_: mywork = Wor
35、k() mywork.hour = 9 mywork.WriteProgram() mywork.hour =14 mywork.WriteProgram()十三、適配器模式模式特點:將一個類的接口轉(zhuǎn)換成為客戶希望的另外一個接口。程序?qū)嵗河脩敉ㄟ^適配器使用一個類的方法。代碼特點:無適配器模式class Target: def Request(): print common request.class Adaptee(Target): def SpecificRequest(self): print specific request.class Adapter(Target): def _in
36、it_(self,ada): self.adaptee = ada def Request(self): self.adaptee.SpecificRequest()if _name_ = _main_: adaptee = Adaptee() adapter = Adapter(adaptee) adapter.Request()十四、備忘錄模式模式特點:在不破壞封裝性的前提下捕獲一個對象的內(nèi)部狀態(tài),并在該對象之外保存這個狀態(tài),以后可以將對象恢復到這個狀態(tài)。程序?qū)嵗簩riginator對象的狀態(tài)封裝成Memo對象保存在Caretaker內(nèi)代碼特點:無備忘錄模式class Originat
37、or: def _init_(self): self.state = def Show(self): print self.state def 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 = on on.Show(
38、) c = Caretaker() c.memo=on.CreateMemo() on.state=off on.Show() on.SetMemo(c.memo) on.Show()十五、組合模式模式特點:將對象組合成成樹形結構以表示“部分-整體”的層次結構程序?qū)嵗汗救藛T的組織結構代碼特點:無組合模式class Component: def _init_(self,strName): self.m_strName = strName def Add(self,com): pass def Display(self,nDepth): passclass Leaf(Component): d
39、ef Add(self,com): print leaf cant add def Display(self,nDepth): strtemp = for i in range(nDepth): strtemp=strtemp+- strtemp=strtemp+self.m_strName print strtempclass Composite(Component): def _init_(self,strName): self.m_strName = strName self.c = def Add(self,com): self.c.append(com) def Display(se
40、lf,nDepth): strtemp= for i in range(nDepth): strtemp=strtemp+- strtemp=strtemp+self.m_strName print strtemp for com in self.c: com.Display(nDepth+2)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);十六、迭代器模式模式特點:提供方法順序訪
41、問一個聚合對象中各元素,而又不暴露該對象的內(nèi)部表示說明:這個模式?jīng)]有寫代碼實現(xiàn),原因是使用Python的列表和for . in list就能夠完成不同類型對象聚合的迭代功能了。十七、單例模式模式特點:保證類僅有一個實例,并提供一個訪問它的全局訪問點。說明: 為了實現(xiàn)單例模式費了不少工夫,后來查到一篇博文對此有很詳細的介紹,而且實現(xiàn)方式也很豐富,通過對代碼的學習可以了解更多Python的用法。以下的代碼出自GhostFromHeaven的專欄,地址:/ghostfromheaven/article/details/。不過正如其作者在Python單例模式終極版
42、所說:我要問的是,Python真的需要單例模式嗎?我指像其他編程語言中的單例模式。答案是:不需要!因為,Python有模塊(module),最pythonic的單例典范。模塊在在一個應用程序中只有一份,它本身就是單例的,將你所需要的屬性和方法,直接暴露在模塊中變成模塊的全局變量和方法即可!單例模式(四種方法)#-*- encoding=utf-8 -*-print -方法1-#方法1,實現(xiàn)_new_方法#并在將一個類的實例綁定到類變量_instance上,#如果cls._instance為None說明該類還沒有實例化過,實例化該類,并返回#如果cls._instance不為None,直接返回c
43、ls._instanceclass 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 = 3print one.a#3#one和two完全相同,可以用id(), =, is
44、檢測print id(one)#print id(two)#print one = two#Trueprint one is two#Trueprint -方法2-#方法2,共享屬性;所謂單例就是所有引用(實例、對象)擁有相同的狀態(tài)(屬性)和行為(方法)#同一個類的所有實例天然擁有相同的行為(方法),#只需要保證同一個類的所有實例具有相同的狀態(tài)(屬性)即可#所有實例共享屬性的最簡單最直接的方法就是_dict_屬性指向(引用)同一個字典(dict)#可參看:/recipes/66531/class Borg(object): _state =
45、def _new_(cls, *args, *kw): ob = super(Borg, cls)._new_(cls, *args, *kw) ob._dict_ = cls._state return obclass MyClass2(Borg): a = 1one = MyClass2()two = MyClass2()#one和two是兩個不同的對象,id, =, is對比結果可看出two.a = 3print one.a#3print id(one)#print id(two)#print one = two#Falseprint one is two#False#但是one和two具有相同的(同一個_dict_屬性),見:print id(one._dict_)#print id(two._dict_)#print -方法3-#方法3:本質(zhì)上是方法1的升級(或者說高級)版#使用_metaclass_(元類)的高級python用法class Singleton2(type): def _init_(cls, name, bases, dict): super(Singleton2, cls)._init_(name, bases, dict) cls._instance = None def _call_(cls, *args, *kw)
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 保齡球館簡易裝修合同模板
- 預制性塑膠跑道施工方案
- 印染行業(yè)氨水配送協(xié)議
- 咖啡館設計合同樣本
- 旅游景區(qū)裝修安全合同范本
- 汽車維修中心裝修合同樣本
- 保健食品道路運輸合同樣本
- 專業(yè)錄音棚裝修合同模板
- 旅游業(yè)務居間合作協(xié)議模板
- 順義重防腐地坪施工方案
- 《證券法培訓》課件
- 2024年鐵嶺衛(wèi)生職業(yè)學院高職單招語文歷年參考題庫含答案解析
- 大班美術活動:傳統(tǒng)的節(jié)日
- 鞋類代理合作協(xié)議
- 2025理論學習計劃2025年理論中心組學習計劃
- 2025年醫(yī)美醫(yī)院公司組織架構和業(yè)務流程
- 防滑防摔倒安全教育
- 乳腺癌課件教學課件
- 連續(xù)性腎替代治療抗菌藥物劑量調(diào)整專家共識(2024年版)解讀
- 山西省2024年中考物理試題(含答案)
- 春節(jié)節(jié)后收心安全培訓
評論
0/150
提交評論