Python设计模式

设计模式的定义: 为了解决面向对象系统中重要和重复的设计封装在一起的一种代码实现框架, 可以使得代码更加易于扩展和调用

四个基本要素: 模式名称, 问题, 解决方案, 效果

六大原则:

  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)
View Code

一: 单例模式

     定义: 保证一个类只有一个实例, 并提供一个访问它的全局访问点

     适用场景: 当一个类只能有一个实例而客户可以从一个众所周知的访问点访问它时

     优点: 对唯一实例的受控访问, 相当于全局变量, 但是又可以防止此变量被篡改

 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)
View Code

二: 简单工厂模式

     定义: 不直接向客户暴露对象创建的实现细节, 而是通过一个工厂类来负责创建产品类的实例

     角色: 工厂角色, 抽象产品角色, 具体产品角色

     优点: 隐藏了对象创建代码的细节, 客户端不需要修改代码

     缺点: 违反了单一职责原则, 将创建逻辑集中到一个工厂里面, 当要添加新产品时, 违背了开闭原则

 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)
View Code

三: 工厂方法模式

     定义: 定义一个创建对象的接口 (工厂接口), 让子类决定实例化哪个接口

     角色: 抽象工厂角色, 具体工厂角色, 抽象产品角色, 具体产品角色

     适用场景: 需要生产多种, 大量复杂对象的时候, 需要降低代码耦合度的时候, 当系统中的产品类经常需要扩展的时候

     优点: 每个具体的产品都对应一个具体工厂, 不需要修改工厂类的代码, 工厂类可以不知道它所创建的具体的类, 隐藏了对象创建的实现细节

     缺点: 每增加一个具体的产品类, 就必须增加一个相应的工厂类

 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)
View Code

四: 抽象工厂模式

   定义: 定义一个工厂类接口, 让工厂子类来创建一系列相关或相互依赖的对象

     角色: 抽象工厂角色, 具体工厂角色, 抽象产品角色, 具体产品角色, 客户端

     适用场景: 系统要独立于产品的创建和组合时, 强调一系列相关产品的对象设计以便进行联合调试时, 提供一个产品类库, 想隐藏产品的具体实现时

     优点: 将客户端与类的具体实现相分离, 每个工厂创建了一个完整的产品系列, 易于交换产品. 有利于产品的一致性

     缺点: 难以支持新种类的产品

  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()
View Code

 五: 建造者模式

     定义: 将一个复杂对象的构建与它的表示分离, 使得同样的构建过程可以创建不同的表示

     角色: 抽象建造者, 具体建造者, 指挥者, 产品

     适用场景: 当创建复杂对象的算法应该独立于对象的组成部分以及它的装配方式, 当构造过程允许被构造的对象有不同的表示

     优点: 隐藏了一个产品的内部结构和装配过程, 将构造代码与表示代码分开, 可以对构造过程进行更精确的控制

 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)
View Code

 六: 适配器模式

     定义: 将一个接口转换为客户希望的另一个接口, 该模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

     角色: 目标接口, 待适配的类, 适配器

     适用场景: 想使一个已经存在的类, 但其接口不符合你的要求. 想对一些已经存在的子类. 不可能每一个都是用子类来进行适配, 对象适配器可以适配其父类接口

 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)
View Code

 七: 组合模式

     定义: 将对象组合成树形结构以表示 '部分 - 整体' 的层次结构. 组合模式使得用户对单个对象和组合对象的使用具有一致性

     角色: 抽象组件, 叶子组件, 复合组件, 客户端

     适用场景: 表示对象的 '部分 - 整体' 层次结构, 希望用户忽略组合对象与单个对象的不同, 用户统一使用组合结构中的所有对象

     优点: 定义了包含基本对象和组合对象的类层次结构, 简化客户端代码, 即客户端可以一致的使用组合对象和单个对象, 更容易新增新类型的组件

     缺点: 很难限制组合中的组件

 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()
View Code

八: 代理模式

   定义: 为其他对象提供一种代理以控制对特定对象的访问

     角色: 抽象实体, 实体, 代理

     适用场景: 远程代理 (为远程的对象提供代理), 虚代理 (根据需要创建很大的对象, 即懒加载), 保护代理 (控制对原始对象的访问, 用于具有不同访问权限的对象)

     优点: 远程代理 (可以隐藏对象位于远程地址空间的事实), 虚代理 (可对大对象的加载进行优化), 保护代理 (允许在访问一个对象时有一些附加的处理逻辑, 例如权限控制)

 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())
View Code

 九: 观察者模式

     定义: 定义对象间的一种一对多的依赖关系, 当一个对象的状态发生改变时, 所有依赖它的对象都会得到通知并被自动更新. 观察者模式又称为 '发布订阅' 模式

     角色: 抽象主题, 具体主题 (发布者), 抽象观察者, 具体观察者 (订阅者)

     适用场景: 当一个抽象模型有两个方面, 其中一个方面依赖于另一个方面. 将两者封装在独立的对象中以使它们各自独立的改变和复用

                    当一个对象的改变需要同时改变其他对象, 而且不知道具体有多少对象以待改变

                    当一个对象必须通知其他对象, 而又不知道其他对象是谁, 即这些对象之间是解耦的

     优点: 目标和观察者之间的耦合最小, 支持广播通信

     缺点: 多个观察者之间互不知道对方的存在, 因此一个观察者对主题的修改可能造成错误的更新

 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)
View Code

十: 策略模式

     定义: 定义一系列的算法把它们一个个封装起来, 并且使它们可相互替换. 该模式使得算法可独立于使用它的客户而变化

     角色: 抽象策略, 具体策略, 上下文

     适用场景: 许多相关的类仅仅是行为有异, 需使用一个算法的不同变体, 算法使用了客户端无需知道的数据, 一个类中的多个行为以多个条件语句存在可以将其封装在不同的策略类中

     优点: 定义了一系列可重用的算法和行为, 消除了一些条件语句, 可提供相同行为的不同实现

     缺点: 客户必须了解不同的策略, 策略与上下文之间的通信开销, 增加了对象的数目

 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()
View Code

 十一: 责任链模式

     定义: 使多个对象有机会处理请求, 从而避免请求的发布者和接收者之间的耦合关系, 将这些对象连成一条链, 并沿着这条链传递该请求, 直到有一个对象能处理它为止

     角色: 抽象处理者, 具体处理者, 客户端

     适用场景: 有多个对象可以处理一个请求, 哪个对象处理由运行时决定

     优点: 降低耦合度, 一个对象无需知道是其他哪一个对象处理其请求

     缺点: 请求不保证被接收, 链的末端没有处理或链配置错误

 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)
View Code
 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()
View Code

 十二: 迭代器模式

     定义: 提供一种方法可顺序访问一个聚合对象中的各个元素, 而又不需要暴露该对象的内部指示

     适用场景: 实现方法 __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)
View Code

十三: 模板方法模式

     定义: 定义一个操作中算法的骨架, 将一些步骤延迟到子类中, 模板方法使得子类可以不改变一个算法的结构即可重定义该算法某些特定的步骤

     角色: 抽象类 (定义抽象的原子操作, 实现一个模板方法作为算法的骨架), 具体类 (实现原子操作)

     适用场景: 一次性实现一个算法不变的部分, 各个子类的公共行为, 应该被提取出来集中到公共的父类中以避免代码重复, 控制子类扩展

 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')
View Code