設計模式的定義:為了解決面向對象系統中重要和重復的設計封裝在一起的一種代碼實現框架,可以使得代碼更加易於擴展和調用
四個基本要素:模式名稱,問題,解決方案,效果
六大原則:
1.開閉原則:一個軟件實體,如類,模塊和函數應該對擴展開發,對修改關閉.既軟件實體應盡量在不修改原有代碼的情況下進行擴展.
2.里氏替換原則:所有引用父類的方法必須能透明的使用其子類的對象
3.依賴倒置原則:高層模塊不應該依賴底層模塊,二者都應該依賴其抽象,抽象不應該依賴於細節,細節應該依賴抽象,換而言之,要針對接口編程而不是針對實現編程
4.接口隔離原則:使用多個專門的接口,而不是使用單一的總接口,即客戶端不應該依賴那些並不需要的接口
5.迪米特法則:一個軟件實體應該盡可能的少與其他實體相互作用
6.單一直責原則:不要存在多個導致類變更的原因.即一個類只負責一項職責
零:接口
定義:一種特殊的類,聲明了若干方法,要求繼承該接口的類必須實現這種方法
作用:限制繼承接口的類的方法的名稱及調用方式,隱藏了類的內部實現
1 from abc import ABCMeta,abstractmethod 2 3 class Payment(metaclass=ABCMeta): 4 @abstractmethod#定義抽象方法的關鍵字 5 def pay(self,money): 6 pass 7 8 # @abstractmethod 9 # def pay(self,money): 10 # raise NotImplementedError 11 12 class AiliPay(Payment): 13 #子類繼承接口,必須實現接口中定義的抽象方法,否則不能實例化對象 14 def pay(self,money): 15 print('使用支付寶支付%s元'%money) 16 17 class ApplePay(Payment): 18 def pay(self,money): 19 print('使用蘋果支付支付%s元'%money)
一:單例模式
定義:保證一個類只有一個實例,並提供一個訪問它的全局訪問點
適用場景:當一個類只能有一個實例而客戶可以從一個眾所周知的訪問點訪問它時
優點:對唯一實例的受控訪問,相當於全局變量,但是又可以防止此變量被篡改
1 class Singleton(object): 2 #如果該類已經有了一個實例則直接返回,否則創建一個全局唯一的實例 3 def __new__(cls, *args, **kwargs): 4 if not hasattr(cls,'_instance'): 5 cls._instance = super(Singleton,cls).__new__(cls) 6 return cls._instance 7 8 class MyClass(Singleton): 9 def __init__(self,name): 10 if name: 11 self.name = name 12 13 a = MyClass('a') 14 print(a) 15 print(a.name) 16 17 b = MyClass('b') 18 print(b) 19 print(b.name) 20 21 print(a) 22 print(a.name)
二:簡單工廠模式
定義:不直接向客戶暴露對象創建的實現細節,而是通過一個工廠類來負責創建產品類的實例
角色:工廠角色,抽象產品角色,具體產品角色
優點:隱藏了對象創建代碼的細節,客戶端不需要修改代碼
缺點:違反了單一職責原則,將創建邏輯集中到一個工廠里面,當要添加新產品時,違背了開閉原則
1 from abc import ABCMeta,abstractmethod 2 3 class Payment(metaclass=ABCMeta): 4 #抽象產品角色 5 @abstractmethod 6 def pay(self,money): 7 pass 8 9 10 11 class AiliPay(Payment): 12 #具體產品角色 13 def __init__(self,enable_yuebao=False): 14 self.enable_yuebao = enable_yuebao 15 16 def pay(self,money): 17 if self.enable_yuebao: 18 print('使用余額寶支付%s元'%money) 19 else: 20 print('使用支付寶支付%s元'%money) 21 22 class ApplePay(Payment): 23 # 具體產品角色 24 def pay(self,money): 25 print('使用蘋果支付支付%s元'%money) 26 27 class PaymentFactory: 28 #工廠角色 29 def create_payment(self,method): 30 if method == 'alipay': 31 return AiliPay() 32 elif method == 'yuebao': 33 return AiliPay(True) 34 elif method == 'applepay': 35 return ApplePay() 36 else: 37 return NameError 38 39 p = PaymentFactory() 40 f = p.create_payment('yuebao') 41 f.pay(100)
三:工廠方法模式
定義:定義一個創建對象的接口(工廠接口),讓子類決定實例化哪個接口
角色:抽象工廠角色,具體工廠角色,抽象產品角色,具體產品角色
適用場景:需要生產多種,大量復雜對象的時候,需要降低代碼耦合度的時候,當系統中的產品類經常需要擴展的時候
優點:每個具體的產品都對應一個具體工廠,不需要修改工廠類的代碼,工廠類可以不知道它所創建的具體的類,隱藏了對象創建的實現細節
缺點:每增加一個具體的產品類,就必須增加一個相應的工廠類
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__= 'luhj' 4 5 from abc import ABCMeta,abstractmethod 6 7 class Payment(metaclass=ABCMeta): 8 #抽象產品 9 @abstractmethod 10 def pay(self,money): 11 pass 12 13 14 class AliPay(Payment): 15 #具體產品 16 def pay(self,money): 17 print('使用支付寶支付%s元'%money) 18 19 class ApplePay(Payment): 20 def pay(self,money): 21 print('使用蘋果支付支付%s元'%money) 22 23 class PaymentFactory(metaclass=ABCMeta): 24 #抽象工廠 25 @abstractmethod 26 def create_payment(self): 27 pass 28 29 class AliPayFactory(PaymentFactory): 30 #具體工廠 31 def create_payment(self): 32 return AliPay() 33 34 class ApplePayFactory(PaymentFactory): 35 def create_payment(self): 36 return ApplePay() 37 38 af = AliPayFactory() 39 ali = af.create_payment() 40 ali.pay(100) 41 42 #如果要新增支付方式 43 class WechatPay(Payment): 44 def pay(self,money): 45 print('使用微信支付%s元'%money) 46 47 class WechatPayFactory(PaymentFactory): 48 def create_payment(self): 49 return WechatPay() 50 51 w = WechatPayFactory() 52 wc = w.create_payment() 53 wc.pay(200)
四:抽象工廠模式
定義:定義一個工廠類接口,讓工廠子類來創建一系列相關或相互依賴的對象
角色:抽象工廠角色,具體工廠角色,抽象產品角色,具體產品角色,客戶端
適用場景:系統要獨立於產品的創建和組合時,強調一系列相關產品的對象設計以便進行聯合調試時,提供一個產品類庫,想隱藏產品的具體實現時
優點:將客戶端與類的具體實現相分離,每個工廠創建了一個完整的產品系列,易於交換產品.有利於產品的一致性
缺點:難以支持新種類的產品
1 from abc import abstractmethod, ABCMeta 2 3 # ------抽象產品------ 4 class PhoneShell(metaclass=ABCMeta): 5 6 @abstractmethod 7 def show_shell(self): 8 pass 9 10 class CPU(metaclass=ABCMeta): 11 @abstractmethod 12 def show_cpu(self): 13 pass 14 15 class OS(metaclass=ABCMeta): 16 @abstractmethod 17 def show_os(self): 18 pass 19 20 # ------抽象工廠------ 21 class PhoneFactory(metaclass=ABCMeta): 22 23 @abstractmethod 24 def make_shell(self): 25 pass 26 27 @abstractmethod 28 def make_cpu(self): 29 pass 30 31 @abstractmethod 32 def make_os(self): 33 pass 34 35 # ------具體產品------ 36 class SmallShell(PhoneShell): 37 def show_shell(self): 38 print('小手機殼') 39 40 class BigShell(PhoneShell): 41 def show_shell(self): 42 print('大手機殼') 43 44 class AppleShell(PhoneShell): 45 def show_shell(self): 46 print('蘋果機殼') 47 48 class SnapDragonCPU(CPU): 49 def show_cpu(self): 50 print('驍龍CPU') 51 52 class MediaTekCPU(CPU): 53 def show_cpu(self): 54 print('聯發科CPU') 55 56 class AppleCPU(CPU): 57 def show_cpu(self): 58 print('蘋果CPU') 59 60 class Andriod(OS): 61 def show_os(self): 62 print('安卓系統') 63 64 class IOS(OS): 65 def show_os(self): 66 print('iOS系統') 67 68 # ------具體工廠------ 69 class MiFactory(PhoneFactory): 70 def make_shell(self): 71 return BigShell() 72 73 def make_os(self): 74 return Andriod() 75 76 def make_cpu(self): 77 return SnapDragonCPU() 78 79 class HuaweiFactory(PhoneFactory): 80 def make_shell(self): 81 return SmallShell() 82 83 def make_os(self): 84 return Andriod() 85 86 def make_cpu(self): 87 return MediaTekCPU() 88 89 class AppleFactory(PhoneFactory): 90 def make_shell(self): 91 return AppleShell() 92 93 def make_os(self): 94 return IOS() 95 96 def make_cpu(self): 97 return AppleCPU() 98 99 # ------客戶端------ 100 class Phone: 101 def __init__(self,shell,os,cpu): 102 self.shell=shell 103 self.os=os 104 self.cpu=cpu 105 106 def show_info(self): 107 print('手機信息') 108 self.cpu.show_cpu() 109 self.shell.show_shell() 110 self.os.show_os() 111 112 def make_phone(factory): 113 cpu = factory.make_cpu() 114 os = factory.make_os() 115 shell = factory.make_shell() 116 return Phone(shell,os,cpu) 117 118 p1 = make_phone(AppleFactory()) 119 p1.show_info()
五:建造者模式
定義:將一個復雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示
角色:抽象建造者,具體建造者,指揮者,產品
適用場景:當創建復雜對象的算法應該獨立於對象的組成部分以及它的裝配方式,當構造過程允許被構造的對象有不同的表示
優點:隱藏了一個產品的內部結構和裝配過程,將構造代碼與表示代碼分開,可以對構造過程進行更精確的控制
1 from abc import abstractmethod, ABCMeta 2 3 #------產品------ 4 class Player: 5 def __init__(self,face=None, body=None, arm=None, leg=None): 6 self.face =face 7 self.body=body 8 self.arm=arm 9 self.leg=leg 10 11 def __str__(self): 12 return '%s,%s,%s,%s'%(self.face,self.body,self.arm,self.leg) 13 14 #------建造者------ 15 class PlayerBuilder(metaclass=ABCMeta): 16 @abstractmethod 17 def build_face(self): 18 pass 19 20 @abstractmethod 21 def build_body(self): 22 pass 23 24 @abstractmethod 25 def build_arm(self): 26 pass 27 28 @abstractmethod 29 def build_leg(self): 30 pass 31 32 @abstractmethod 33 def get_player(self): 34 pass 35 36 #------具體建造者------ 37 class BeautifulWoman(PlayerBuilder): 38 def __init__(self): 39 self.player=Player() 40 41 def build_face(self): 42 self.player.face = '白臉蛋' 43 44 def build_body(self): 45 self.player.body = '好身材' 46 47 def build_arm(self): 48 self.player.arm = '細胳膊' 49 50 def build_leg(self): 51 self.player.leg = '大長腿' 52 53 def get_player(self): 54 return self.player 55 56 #------指揮者------ 57 class PlayerDirecter: 58 def build_player(self,builder): 59 builder.build_face() 60 builder.build_body() 61 builder.build_arm() 62 builder.build_leg() 63 return builder.get_player() 64 65 director = PlayerDirecter() 66 builder = BeautifulWoman() 67 p = director.build_player(builder) 68 print(p)
六:適配器模式
定義:將一個接口轉換為客戶希望的另一個接口,該模式使得原本由於接口不兼容而不能一起工作的那些類可以一起工作
角色:目標接口,待適配的類,適配器
適用場景:想使一個已經存在的類,但其接口不符合你的要求.想對一些已經存在的子類.不可能每一個都是用子類來進行適配,對象適配器可以適配其父類接口

1 from abc import abstractmethod, ABCMeta 2 3 4 class Payment(metaclass=ABCMeta): 5 @abstractmethod 6 def pay(self, money): 7 raise NotImplementedError 8 9 10 class Alipay(Payment): 11 def pay(self, money): 12 print("支付寶支付%s元"%money) 13 14 15 class ApplePay(Payment): 16 def pay(self, money): 17 print("蘋果支付%s元"%money) 18 19 #------待適配的類----- 20 class WeChatPay: 21 def fuqian(self,money): 22 print('微信支付%s元'%money) 23 24 #------類適配器------ 25 class RealWeChatPay(Payment,WeChatPay): 26 def pay(self, money): 27 return self.fuqian(money) 28 29 #-----對象適配器----- 30 class PayAdapter(Payment): 31 def __init__(self,payment): 32 self.payment=payment 33 def pay(self, money): 34 return self.payment.fuqian(money) 35 36 #RealWeChatPay().pay(100) 37 38 p=PayAdapter(WeChatPay()) 39 p.pay(200)
七:組合模式
定義:將對象組合成樹形結構以表示'部分-整體'的層次結構.組合模式使得用戶對單個對象和組合對象的使用具有一致性
角色:抽象組件,葉子組件,復合組件,客戶端
適用場景:表示對象的'部分-整體'層次結構,希望用戶忽略組合對象與單個對象的不同,用戶統一使用組合結構中的所有對象
優點:定義了包含基本對象和組合對象的類層次結構,簡化客戶端代碼,即客戶端可以一致的使用組合對象和單個對象,更容易新增新類型的組件
缺點:很難限制組合中的組件
1 from abc import abstractmethod, ABCMeta 2 3 #-------抽象組件-------- 4 class Graph(metaclass=ABCMeta): 5 6 @abstractmethod 7 def draw(self): 8 pass 9 10 @abstractmethod 11 def add(self,graph): 12 pass 13 14 def get_children(self): 15 pass 16 17 #---------葉子組件-------- 18 class Point(Graph): 19 def __init__(self,x,y): 20 self.x = x 21 self.y = y 22 23 def draw(self): 24 print(self) 25 26 def add(self,graph): 27 raise TypeError 28 29 def get_children(self): 30 raise TypeError 31 32 def __str__(self): 33 return '點(%s,%s)'%(self.x,self.y) 34 35 36 class Line(Graph): 37 38 def __init__(self,p1,p2): 39 self.p1 = p1 40 self.p2 = p2 41 42 def draw(self): 43 print(self) 44 45 def add(self,graph): 46 raise TypeError 47 48 def get_children(self): 49 raise TypeError 50 51 def __str__(self): 52 return '線段(%s,%s)'%(self.p1,self.p2) 53 54 #--------復合組件--------- 55 class Picture(Graph): 56 def __init__(self): 57 self.children = [] 58 59 def add(self,graph): 60 self.children.append(graph) 61 62 def get_children(self): 63 return self.children 64 65 def draw(self): 66 print('-----復合圖形-----') 67 for g in self.children: 68 g.draw() 69 print('結束') 70 71 72 #---------客戶端--------- 73 pic1 = Picture() 74 point = Point(2,3) 75 pic1.add(point) 76 pic1.add(Line(Point(1,2),Point(4,5))) 77 pic1.add(Line(Point(0,1),Point(2,1))) 78 79 pic2 = Picture() 80 pic2.add(Point(-2,-1)) 81 pic2.add(Line(Point(0,0),Point(1,1))) 82 83 pic = Picture() 84 pic.add(pic1) 85 pic.add(pic2) 86 87 pic.draw()
八:代理模式
定義:為其他對象提供一種代理以控制對特定對象的訪問
角色:抽象實體,實體,代理
適用場景:遠程代理(為遠程的對象提供代理),虛代理(根據需要創建很大的對象,即懶加載),保護代理(控制對原始對象的訪問,用於具有不同訪問權限的對象)
優點:遠程代理(可以隱藏對象位於遠程地址空間的事實),虛代理(可對大對象的加載進行優化),保護代理(允許在訪問一個對象時有一些附加的處理邏輯,例如權限控制)
1 from abc import ABCMeta, abstractmethod 2 3 #抽象實體 4 class Subject(metaclass=ABCMeta): 5 @abstractmethod 6 def get_content(self): 7 pass 8 9 #實體 10 class RealSubject(Subject): 11 def __init__(self,filename): 12 print('讀取文件%s內容'%filename) 13 f = open(filename) 14 self.content = f.read() 15 f.close() 16 17 def get_content(self): 18 return self.content 19 20 #遠程代理 21 class ProxyA(Subject): 22 def __init__(self,filename): 23 self.subj =RealSubject(filename) 24 def get_content(self): 25 return self.subj.get_content() 26 27 #虛代理 28 class ProxyB(Subject): 29 def __init__(self,filename): 30 self.filename = filename 31 self.subj = None 32 def get_content(self): 33 if not self.subj: 34 self.subj = RealSubject(self.filename) 35 return self.subj.get_content() 36 37 #保護代理 38 class ProxyC(Subject): 39 def __init__(self,filename): 40 self.subj = RealSubject(filename) 41 def get_content(self): 42 return '???' 43 44 45 #客戶端 46 filename = 'abc.txt' 47 username = input('>>') 48 if username!='alex': 49 p=ProxyC(filename) 50 else: 51 p=ProxyB(filename) 52 53 print(p.get_content())
九:觀察者模式
定義:定義對象間的一種一對多的依賴關系,當一個對象的狀態發生改變時,所有依賴它的對象都會得到通知並被自動更新.觀察者模式又稱為'發布訂閱'模式
角色:抽象主題,具體主題(發布者),抽象觀察者,具體觀察者(訂閱者)
適用場景:當一個抽象模型有兩個方面,其中一個方面依賴於另一個方面.將兩者封裝在獨立的對象中以使它們各自獨立的改變和復用
當一個對象的改變需要同時改變其他對象,而且不知道具體有多少對象以待改變
當一個對象必須通知其他對象,而又不知道其他對象是誰,即這些對象之間是解耦的
優點:目標和觀察者之間的耦合最小,支持廣播通信
缺點:多個觀察者之間互不知道對方的存在,因此一個觀察者對主題的修改可能造成錯誤的更新
1 from abc import ABCMeta, abstractmethod 2 3 #抽象主題 4 class Oberserver(metaclass=ABCMeta): 5 @abstractmethod 6 def update(self): 7 pass 8 9 #具體主題 10 class Notice: 11 def __init__(self): 12 self.observers = [] 13 14 def attach(self,obs): 15 self.observers.append(obs) 16 17 def detach(self,obs): 18 self.observers.remove(obs) 19 20 def notify(self): 21 for obj in self.observers: 22 obj.update(self) 23 24 #抽象觀察者 25 class ManagerNotice(Notice): 26 def __init__(self,company_info=None): 27 super().__init__() 28 self.__company_info = company_info 29 30 @property 31 def company_info(self): 32 return self.__company_info 33 34 @company_info.setter 35 def company_info(self,info): 36 self.__company_info = info 37 self.notify() 38 39 #具體觀察者 40 class Manager(Oberserver): 41 def __init__(self): 42 self.company_info = None 43 def update(self,noti): 44 self.company_info = noti.company_info 45 46 #消息訂閱-發送 47 notice = ManagerNotice() 48 49 alex=Manager() 50 tony=Manager() 51 52 notice.attach(alex) 53 notice.attach(tony) 54 notice.company_info="公司運行良好" 55 print(alex.company_info) 56 print(tony.company_info) 57 58 notice.company_info="公司將要上市" 59 print(alex.company_info) 60 print(tony.company_info) 61 62 notice.detach(tony) 63 notice.company_info="公司要破產了,趕快跑路" 64 print(alex.company_info) 65 print(tony.company_info)
十:策略模式
定義:定義一系列的算法把它們一個個封裝起來,並且使它們可相互替換.該模式使得算法可獨立於使用它的客戶而變化
角色:抽象策略,具體策略,上下文
適用場景:許多相關的類僅僅是行為有異,需使用一個算法的不同變體,算法使用了客戶端無需知道的數據,一個類中的多個行為以多個條件語句存在可以將其封裝在不同的策略類中
優點:定義了一系列可重用的算法和行為,消除了一些條件語句,可提供相同行為的不同實現
缺點:客戶必須了解不同的策略,策略與上下文之間的通信開銷,增加了對象的數目
1 from abc import ABCMeta, abstractmethod 2 import random 3 4 #抽象策略 5 class Sort(metaclass=ABCMeta): 6 @abstractmethod 7 def sort(self,data): 8 pass 9 10 #具體策略 11 class QuickSort(Sort): 12 13 def quick_sort(self,data,left,right): 14 if left<right: 15 mid = self.partation(data,left,right) 16 self.quick_sort(data,left,mid-1) 17 self.quick_sort(data,mid+1,right) 18 19 def partation(self,data,left,right): 20 tmp = data[left] 21 while left < right: 22 while left<right and data[right]>=tmp: 23 right -= 1 24 data[left] = data[right] 25 26 while left<right and data[left]<=tmp: 27 left += 1 28 data[right] = data[left] 29 data[left] = tmp 30 return left 31 32 def sort(self,data): 33 print("快速排序") 34 return self.quick_sort(data,0,len(data)-1) 35 36 class MergeSort(Sort): 37 def merge(self,data,low,mid,high): 38 i = low 39 j = mid+1 40 ltmp = [] 41 while i <= mid and j <= high: 42 if data[i] <= data[j]: 43 ltmp.append(data[i]) 44 i+=1 45 else: 46 ltmp.append(data[j]) 47 j+=1 48 while i <= mid: 49 ltmp.append(data[i]) 50 i+=1 51 while j <= high: 52 ltmp.append(data[j]) 53 j+=1 54 data[low:high+1]=ltmp 55 56 def merge_sort(self,data,low,high): 57 if low<high: 58 mid = (low+high)//2 59 self.merge_sort(data,low,mid) 60 self.merge_sort(data,mid+1,high) 61 self.merge(data,low,mid,high) 62 def sort(self,data): 63 print("歸並排序") 64 return self.merge_sort(data,0,len(data)-1) 65 66 #上下文 67 class Context: 68 def __init__(self,data,strategy=None): 69 self.data=data 70 self.strategy=strategy 71 72 def set_strategy(self,strategy): 73 self.strategy=strategy 74 75 def do_strategy(self): 76 if self.strategy: 77 self.strategy.sort(self.data) 78 else: 79 raise TypeError 80 81 82 li = list(range(100000)) 83 random.shuffle(li) 84 context = Context(li,MergeSort()) 85 context.do_strategy() 86 87 random.shuffle(context.data) 88 context.set_strategy(QuickSort()) 89 context.do_strategy()
十一:責任鏈模式
定義:使多個對象有機會處理請求,從而避免請求的發布者和接收者之間的耦合關系,將這些對象連成一條鏈,並沿着這條鏈傳遞該請求,直到有一個對象能處理它為止
角色:抽象處理者,具體處理者,客戶端
適用場景:有多個對象可以處理一個請求,哪個對象處理由運行時決定
優點:降低耦合度,一個對象無需知道是其他哪一個對象處理其請求
缺點:請求不保證被接收,鏈的末端沒有處理或鏈配置錯誤
1 from abc import ABCMeta, abstractmethod 2 3 class Handler(metaclass=ABCMeta): 4 @abstractmethod 5 def handel_leave(self,day): 6 pass 7 8 class GeneralManagerHandler(Handler): 9 def handel_leave(self,day): 10 if day < 10: 11 print('總經理批准請假%s天'%day) 12 13 else: 14 print('不能請假') 15 16 class DepartmentManagerHandler(Handler): 17 def __init__(self): 18 self.successor = GeneralManagerHandler() 19 def handel_leave(self,day): 20 if day < 7: 21 print('部門經理批准請假%s天' % day) 22 else: 23 print('部門經理無權批假') 24 self.successor.handel_leave(day) 25 26 class ProjectDirectorHandler(Handler): 27 def __init__(self): 28 self.successor = DepartmentManagerHandler() 29 def handel_leave(self,day): 30 if day < 3: 31 print('項目經理批准請假%s天' % day) 32 else: 33 print('項目經理無權批假') 34 self.successor.handel_leave(day) 35 36 day = 6 37 h = ProjectDirectorHandler() 38 h.handel_leave(day)
1 from abc import ABCMeta, abstractmethod 2 #--模仿js事件處理 3 class Handler(metaclass=ABCMeta): 4 @abstractmethod 5 def add_event(self,func): 6 pass 7 8 @abstractmethod 9 def handler(self): 10 pass 11 12 class BodyHandler(Handler): 13 def __init__(self): 14 self.func = None 15 16 def add_event(self,func): 17 self.func = func 18 19 def handler(self): 20 if self.func: 21 return self.func() 22 else: 23 print('已經是最后一級,無法處理') 24 25 26 class ElementHandler(Handler): 27 28 def __init__(self,successor): 29 self.func = None 30 self.successor = successor 31 32 def add_event(self,func): 33 self.func = func 34 35 def handler(self): 36 if self.func: 37 return self.func() 38 else: 39 return self.successor.handler() 40 41 42 #客戶端 43 body = {'type': 'body', 'name': 'body', 'children': [], 'father': None} 44 45 div = {'type': 'div', 'name': 'div', 'children': [], 'father': body} 46 47 a = {'type': 'a', 'name': 'a', 'children': [], 'father': div} 48 49 body['children'] = div 50 div['children'] = a 51 52 body['event_handler'] = BodyHandler() 53 div['event_handler'] = ElementHandler(div['father']['event_handler']) 54 a['event_handler'] = ElementHandler(a['father']['event_handler']) 55 56 def attach_event(element,func): 57 element['event_handler'].add_event(func) 58 59 #測試 60 def func_div(): 61 print("這是給div的函數") 62 63 def func_a(): 64 print("這是給a的函數") 65 66 def func_body(): 67 print("這是給body的函數") 68 69 attach_event(div,func_div) 70 #attach_event(a,func_a) 71 attach_event(body,func_body) 72 73 a['event_handler'].handler()
十二:迭代器模式
定義:提供一種方法可順序訪問一個聚合對象中的各個元素,而又不需要暴露該對象的內部指示
適用場景:實現方法__iter__,__next__
1 class LinkedList: 2 class Node: 3 def __init__(self,item=None): 4 self.item=item 5 self.next=None 6 class LinkedListIterator: 7 def __init__(self,node): 8 self.node = node 9 #實現next方法,返回下一個元素 10 def __next__(self): 11 if self.node: 12 cur_node = self.node 13 self.node = cur_node.next 14 return cur_node.item 15 16 def __iter__(self): 17 return self 18 def __init__(self,iterable=None): 19 self.head = LinkedList.Node(0) 20 self.tail = self.head 21 self.extend(iterable) 22 23 #鏈表尾部追加元素 24 def append(self,obj): 25 s = LinkedList.Node(obj) 26 self.tail.next = s 27 self.tail = s 28 #鏈表自動增加長度 29 def extend(self,iterable): 30 for obj in iterable: 31 self.append(obj) 32 self.head.item += len(iterable) 33 34 def __iter__(self): 35 return self.LinkedListIterator(self.head.next) 36 37 def __len__(self): 38 return self.head.item 39 40 def __str__(self): 41 return '<<'+', '.join(map(str,self)) + '>>' 42 43 li = [i for i in range(100)] 44 lk = LinkedList(li) 45 print(lk)
十三:模板方法模式
定義:定義一個操作中算法的骨架,將一些步驟延遲到子類中,模板方法使得子類可以不改變一個算法的結構即可重定義該算法某些特定的步驟
角色:抽象類(定義抽象的原子操作,實現一個模板方法作為算法的骨架),具體類(實現原子操作)
適用場景:一次性實現一個算法不變的部分,各個子類的公共行為,應該被提取出來集中到公共的父類中以避免代碼重復,控制子類擴展
1 from abc import ABCMeta, abstractmethod 2 3 #----抽象類----- 4 class IOHandler(metaclass=ABCMeta): 5 @abstractmethod 6 def open(self,name): 7 pass 8 9 @abstractmethod 10 def deal(self,change): 11 pass 12 13 @abstractmethod 14 def close(self): 15 pass 16 #在父類中定義了子類的行為 17 def process(self,name,change): 18 self.open(name) 19 self.deal(change) 20 self.close() 21 22 #子類中只需要實現部分算法,而不需要實現所有的邏輯 23 #-----具體類-------- 24 class FileHandler(IOHandler): 25 def open(self,name): 26 self.file = open(name,'w') 27 28 def deal(self,change): 29 self.file.write(change) 30 31 def close(self): 32 self.file.close() 33 34 f = FileHandler() 35 f.process('abc.txt','hello')
