用python实现设计模式

Patterns mean “I have run out of language.” - Rich Hickey

之前学习设计模式的时候总是没有什么感觉,因为记性不好一直没记住多少。python不像java中比较强调设计模式(编程套路),动态语言也内置了像是装饰器、迭代器等模式,另外python中的『一切皆对象』、鸭子类型等也导致python中实现的设计模式和其他语言有些差别。根据YAGNI(you aren’t gonna need it)和KISS(Keep it simple sutpid)原则,如果能用简单易懂的方式实现,最好不要滥用设计模式以免增加复杂度和维护难度。本博客是《Mastering Python Design Patterns》的读书笔记,涵盖大部分设计模式(力求pythonic实现),有兴趣可以参考下,代码示例版本为python3.5.2。(3.6都发布了,已经被时代遗弃😢……)


1: The Fctory Pattern(工厂模式: 解决对象创建问题)

先来看三种创建模式中的第一种工厂模式。 解释:处理对象创建,客户端可以申请一个对象而不用知道对象被哪个class创建。可以方便地解耦对象的使用和创建。有两种实现,工厂方法和抽象工厂.

Method(工厂方法):

执行单独的函数,通过传参提供需要的对象的信息。通过一个demo看看例子:

  1. import json
  2. import xml.etree.ElementTree as etree
  3. class JSONConnector:
  4. def __init__(self, filepath):
  5. self.data = dict()
  6. with open(filepath, mode='r', encoding='utf8') as f:
  7. self.data = json.load(f)
  8. @property
  9. def parsed_data(self):
  10. return self.data
  11. class XMLConnector:
  12. def __init__(self, filepath):
  13. self.tree = etree.parse(filepath)
  14. @property
  15. def parsed_data(self):
  16. return self.tree
  17. def connection_factory(filepath):
  18. """ 工厂方法 """
  19. if filepath.endswith('json'):
  20. connector = JSONConnector
  21. elif filepath.endswith('xml'):
  22. connector = XMLConnector
  23. else:
  24. raise ValueError('Cannot connect to {}'.format(filepath))
  25. return connector(filepath)

Abstract Factory(抽象工厂: 解决复杂对象创建问题)

工厂方法适合对象种类较少的情况,如果有多种不同类型对象需要创建,使用抽象工厂模式。以实现一个游戏的例子说明,在一个抽象工厂类里实现多个关联对象的创建:

  1. class Frog:
  2. def __init__(self, name):
  3. self.name = name
  4. def __str__(self):
  5. return self.name
  6. def interact_with(self, obstacle):
  7. """ 不同类型玩家遇到的障碍不同 """
  8. print('{} the Frog encounters {} and {}!'.format(
  9. self, obstacle, obstacle.action()))
  10. class Bug:
  11. def __str__(self):
  12. return 'a bug'
  13. def action(self):
  14. return 'eats it'
  15. class FrogWorld:
  16. def __init__(self, name):
  17. print(self)
  18. self.player_name = name
  19. def __str__(self):
  20. return '\n\n\t----Frog World -----'
  21. def make_character(self):
  22. return Frog(self.player_name)
  23. def make_obstacle(self):
  24. return Bug()
  25. class Wizard:
  26. def __init__(self, name):
  27. self.name = name
  28. def __str__(self):
  29. return self.name
  30. def interact_with(self, obstacle):
  31. print('{} the Wizard battles against {} and {}!'.format(
  32. self, obstacle, obstacle.action()))
  33. class Ork:
  34. def __str__(self):
  35. return 'an evil ork'
  36. def action(self):
  37. return 'kill it'
  38. class WizardWorld:
  39. def __init__(self, name):
  40. print(self)
  41. self.player_name = name
  42. def __str__(self):
  43. return '\n\n\t------ Wizard World -------'
  44. def make_character(self):
  45. return Wizard(self.player_name)
  46. def make_obstacle(self):
  47. return Ork()
  48. class GameEnvironment:
  49. """ 抽象工厂,根据不同的玩家类型创建不同的角色和障碍 (游戏环境)
  50. 这里可以根据年龄判断,成年人返回『巫师』游戏,小孩返回『青蛙过河』游戏"""
  51. def __init__(self, factory):
  52. self.hero = factory.make_character()
  53. self.obstacle = factory.make_obstacle()
  54. def play(self):
  55. self.hero.interact_with(self.obstacle)

2: The Builder Pattern(构造模式: 控制复杂对象的构造)

当对象需要多个部分组合起来一步步创建,并且创建和表示分离的时候。可以这么理解,你要买电脑,工厂模式直接返回一个你需要型号的电脑,但是构造模式允许你自定义电脑各种配置类型,组装完成后给你。这个过程你可以传入builder从而自定义创建的方式。

  1. # factory pattern
  2. MINI14 = '1.4GHz Mac mini'
  3. class AppleFactory:
  4. class MacMini14:
  5. def __init__(self):
  6. self.memory = 4 # in gigabytes
  7. self.hdd = 500 # in gigabytes
  8. self.gpu = 'Intel HD Graphics 5000'
  9. def __str__(self):
  10. info = ('Model: {}'.format(MINI14),
  11. 'Memory: {}GB'.format(self.memory),
  12. 'Hard Disk: {}GB'.format(self.hdd),
  13. 'Graphics Card: {}'.format(self.gpu))
  14. return '\n'.join(info)
  15. def build_computer(self, model):
  16. if model == MINI14:
  17. return self.MacMini14()
  18. else:
  19. print("I don't know how to build {}".format(model))
  20. # 使用工厂
  21. afac = AppleFactory()
  22. mac_mini = afac.build_computer(MINI14)
  23. print(mac_mini)
  24. # builder模式
  25. class Computer:
  26. def __init__(self, serial_number):
  27. self.serial = serial_number
  28. self.memory = None # in gigabytes
  29. self.hdd = None # in gigabytes
  30. self.gpu = None
  31. def __str__(self):
  32. info = ('Memory: {}GB'.format(self.memory),
  33. 'Hard Disk: {}GB'.format(self.hdd),
  34. 'Graphics Card: {}'.format(self.gpu))
  35. return '\n'.join(info)
  36. class ComputerBuilder:
  37. def __init__(self):
  38. self.computer = Computer('AG23385193')
  39. def configure_memory(self, amount):
  40. self.computer.memory = amount
  41. def configure_hdd(self, amount):
  42. self.computer.hdd = amount
  43. def configure_gpu(self, gpu_model):
  44. self.computer.gpu = gpu_model
  45. class HardwareEngineer:
  46. def __init__(self):
  47. self.builder = None
  48. def construct_computer(self, memory, hdd, gpu):
  49. self.builder = ComputerBuilder()
  50. [step for step in (self.builder.configure_memory(memory),
  51. self.builder.configure_hdd(hdd),
  52. self.builder.configure_gpu(gpu))]
  53. @property
  54. def computer(self):
  55. return self.builder.computer
  56. # 使用buidler,可以创建多个builder类实现不同的组装方式
  57. engineer = HardwareEngineer()
  58. engineer.construct_computer(hdd=500, memory=8, gpu='GeForce GTX 650 Ti')
  59. computer = engineer.computer
  60. print(computer)

3:The Prototype Pattern(原型模式:解决对象拷贝问题)

这是创建模式中的最后一个,用来克隆一个对象,有点像生物学中的有丝分裂。我们可以使用python内置的copy模块实现。拷贝分为深拷贝和浅拷贝,深拷贝会递归复制并创建新对象,而浅拷贝会利用引用指向同一个对象.深拷贝的优点是对象之间互不影响,但是会耗费资源,创建比较耗时;如果不会修改对象可以使用浅拷贝,更加节省资源和创建时间。

  • “A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.”
  1. import copy
  2. from collections import OrderedDict
  3. class Book:
  4. def __init__(self, name, authors, price, **rest):
  5. '''Examples of rest: publisher, length, tags, publication
  6. date'''
  7. self.name = name
  8. self.authors = authors
  9. self.price = price # in US dollars
  10. self.__dict__.update(rest)
  11. def __str__(self):
  12. mylist = []
  13. ordered = OrderedDict(sorted(self.__dict__.items()))
  14. for i in ordered.keys():
  15. mylist.append('{}: {}'.format(i, ordered[i]))
  16. if i == 'price':
  17. mylist.append('$')
  18. mylist.append('\n')
  19. return ''.join(mylist)
  20. class Prototype:
  21. def __init__(self):
  22. self.objects = {}
  23. def register(self, identifier, obj):
  24. self.objects[identifier] = obj
  25. def unregister(self, identifier):
  26. del self.objects[identifier]
  27. def clone(self, identifier, **attr):
  28. """ 实现对象拷贝 """
  29. found = self.objects.get(identifier)
  30. if not found:
  31. raise ValueError('Incorrect object identifier: {}'.format(identifier))
  32. obj = copy.deepcopy(found)
  33. obj.__dict__.update(attr) # 实现拷贝时自定义更新
  34. return obj
  35. def main():
  36. b1 = Book('The C Programming Language', ('Brian W. Kernighan', 'Dennis M.Ritchie'),
  37. price=118, publisher='Prentice Hall', length=228, publication_date='1978-02-22',
  38. tags=('C', 'programming', 'algorithms', 'data structures'))
  39. prototype = Prototype()
  40. cid = 'k&r-first'
  41. prototype.register(cid, b1)
  42. b2 = prototype.clone(cid, name='The C Programming Language (ANSI)', price=48.99, length=274,
  43. publication_date='1988-04-01', edition=2)
  44. for i in (b1, b2):
  45. print(i)
  46. print("ID b1 : {} != ID b2 : {}".format(id(b1), id(b2)))

4: The Adapter Pattern(适配器模式: 解决接口不兼容问题)

开始介绍结构型设计模式,结构型设计模式通过组合对象来实现新功能。适配器模式通过引入间接层来实现不兼容接口之间的适配。现实中最好的例子就是手机充电口,不同型号安卓手机都可以用同样的充电线充电。在python中可以通过继承实现适配,也可以通过使用class的__dict__属性。 开闭原则:适配器模式和OOP中的开闭原则关系密切,开闭原则强调对扩展开放,对修改关闭。通过适配器模式我们可以通过创建适配器模式在不修改原有类代码的情况下实现新的功能。

  1. class Computer:
  2. def __init__(self, name):
  3. self.name = name
  4. def __str__(self):
  5. return 'the {} computer'.format(self.name)
  6. def execute(self):
  7. """ call by client code """
  8. return 'execute a program'
  9. class Synthesizer:
  10. def __init__(self, name):
  11. self.name = name
  12. def __str__(self):
  13. return 'the {} synthesizer'.format(self.name)
  14. def play(self):
  15. return 'is playing an electroinc song'
  16. class Human:
  17. def __init__(self, name):
  18. self.name = name
  19. def __str__(self):
  20. return 'the {} human'.format(self.name)
  21. def speak(self):
  22. return 'says hello'
  23. class Adapter:
  24. def __init__(self, obj, adapted_methods):
  25. """ 不使用继承,使用__dict__属性实现适配器模式 """
  26. self.obj = obj
  27. self.__dict__.update(adapted_methods)
  28. def __str__(self):
  29. return str(self.obj)
  30. # 适配器使用示例
  31. def main():
  32. objs = [Computer('Asus')]
  33. synth = Synthesizer('moog')
  34. objs.append(Adapter(synth, dict(execute=synth.play)))
  35. human = Human('Wnn')
  36. objs.append(Adapter(human, dict(execute=human.speak)))
  37. for o in objs:
  38. # 用统一的execute适配不同对象的方法,这样在无需修改源对象的情况下就实现了不同对象方法的适配
  39. print('{} {}'.format(str(o), o.execute()))
  40. if __name__ == "__main__":
  41. main()

5: The Decorator Pattern(装饰器模式: 无需子类化实现扩展对象功能问题)

通常给一个对象添加新功能有三种方式: - 直接给对象所属的类添加方法。 - 使用『组合』 - 使用『继承』,优先使用组合而非继承。 装饰器模式提供了第四种选择,通过动态改变对象扩展对象功能。其他编程语言通常使用继承实现装饰器装饰器模式,而python内置了装饰器。装饰器有很多用途,比如数据校验,事务处理,缓存,日志等。比如用装饰器实现一个简单的缓存,python3.5自带了functools.lru_cache

  1. from functools import wraps
  2. def memoize(fn):
  3. known = dict()
  4. @wraps(fn)
  5. def memoizer(*args):
  6. if args not in known:
  7. known[args] = fn(*args)
  8. return known[args]
  9. return memoizer
  10. @memoize
  11. def fibonacci(n):
  12. assert(n >= 0), 'n must be >= 0'
  13. return n if n in (0, 1) else fibonacci(n-1) + fibonacci(n-2)

6: The Facade Pattern(外观模式: 简化复杂对象的访问问题)

外观模式用来简化复杂系统的访问。通过简化的接口只访问需要的部分,隐藏系统复杂性。想象一下公司接线员,虽然公司内部运行机制比较复杂,但是接线员可以迅速帮你解决特定问题。 我们以实现个简单的操作系统示例说明外观模式:

  1. from abc import ABCMeta, abstractmethod
  2. from enum import Enum
  3. State = Enum('State', 'new running sleeping restart zombie')
  4. class Server(metaclass=ABCMeta):
  5. """ 抽象基类 """
  6. @abstractmethod
  7. def __init__(self):
  8. pass
  9. def __str__(self):
  10. return self.name
  11. @abstractmethod
  12. def boot(self):
  13. pass
  14. @abstractmethod
  15. def kill(self, restart=True):
  16. pass
  17. class FileServer(Server):
  18. def __init__(self):
  19. '''actions required for initializing the file server'''
  20. self.name = 'FileServer'
  21. self.state = State.new
  22. def boot(self):
  23. print('booting the {}'.format(self))
  24. '''actions required for booting the file server'''
  25. self.state = State.running
  26. def kill(self, restart=True):
  27. print('Killing {}'.format(self))
  28. '''actions required for killing the file server'''
  29. self.state = State.restart if restart else State.zombie
  30. def create_file(self, user, name, permissions):
  31. '''check validity of permissions, user rights, etc.'''
  32. print("trying to create the file '{}' for user '{}' with permissions {}".format(name, user, permissions))
  33. class ProcessServer(Server):
  34. def __init__(self):
  35. '''actions required for initializing the process server'''
  36. self.name = 'ProcessServer'
  37. self.state = State.new
  38. def boot(self):
  39. print('booting the {}'.format(self))
  40. '''actions required for booting the process server'''
  41. self.state = State.running
  42. def kill(self, restart=True):
  43. print('Killing {}'.format(self))
  44. '''actions required for killing the process server'''
  45. self.state = State.restart if restart else State.zombie
  46. def create_process(self, user, name):
  47. '''check user rights, generate PID, etc.'''
  48. print("trying to create the process '{}' for user '{}'".format(name, user))
  49. class OperatingSystem:
  50. ''' 实现外观模式,外部使用的代码不必知道 FileServer 和 ProcessServer的
  51. 内部机制,只需要通过 OperatingSystem类调用'''
  52. def __init__(self):
  53. self.fs = FileServer()
  54. self.ps = ProcessServer()
  55. def start(self):
  56. """ 被客户端代码使用 """
  57. [i.boot() for i in (self.fs, self.ps)]
  58. def create_file(self, user, name, permissions):
  59. return self.fs.create_file(user, name, permissions)
  60. def create_process(self, user, name):
  61. return self.ps.create_process(user, name)
  62. def main():
  63. os = OperatingSystem()
  64. os.start()
  65. os.create_file('foo', 'hello', '-rw-r-r')
  66. os.create_process('bar', 'ls /tmp')
  67. main()

7: The Flyweight Pattern(享元模式: 实现对象复用从而改善资源使用)

Flyweight design pattern is a technique used to minimize memory usage and improve performance by introducing data sharing between similar objects.

OOP编程中容易出现对象创建带来的性能和内存占用问题,需要满足以下条件:

  • 需要使用大量对象(python里我们可以用__slots__节省内存占用)
  • 对象太多难以存储或解析大量对象。
  • 对象识别不是特别重要,共享对象中对象比较会失败。

经常使用对象池技术来实现共享对象,比如数据库中经常使用连接池来减少开销,预先建立一些连接池,每次取一个连接和数据库交互。

  1. # 使用对象池技术实现享元模式
  2. import random
  3. from enum import Enum
  4. TreeType = Enum('TreeType', 'apple_tree cherry_tree peach_tree')
  5. class Tree:
  6. pool = dict()
  7. def __new__(cls, tree_type):
  8. obj = cls.pool.get(tree_type, None)
  9. if obj is None:
  10. obj = object.__new__(cls)
  11. cls.pool[tree_type] = obj
  12. obj.tree_type = tree_type
  13. return obj
  14. def render(self, age, x, y):
  15. print('render a tree of type {} and age {} at ({}, {})'.format(self.tree_type, age, x, y))
  16. def main():
  17. rnd = random.Random()
  18. age_min, age_max = 1, 30 # in years
  19. min_point, max_point = 0, 100
  20. tree_counter = 0
  21. for _ in range(10):
  22. t1 = Tree(TreeType.apple_tree)
  23. t1.render(rnd.randint(age_min, age_max),
  24. rnd.randint(min_point, max_point),
  25. rnd.randint(min_point, max_point))
  26. tree_counter += 1
  27. for _ in range(3):
  28. t2 = Tree(TreeType.cherry_tree)
  29. t2.render(rnd.randint(age_min, age_max),
  30. rnd.randint(min_point, max_point),
  31. rnd.randint(min_point, max_point))
  32. tree_counter += 1
  33. for _ in range(5):
  34. t3 = Tree(TreeType.peach_tree)
  35. t3.render(rnd.randint(age_min, age_max),
  36. rnd.randint(min_point, max_point),
  37. rnd.randint(min_point, max_point))
  38. tree_counter += 1
  39. print('trees rendered: {}'.format(tree_counter))
  40. print('trees actually created: {}'.format(len(Tree.pool)))
  41. t4 = Tree(TreeType.cherry_tree)
  42. t5 = Tree(TreeType.cherry_tree)
  43. t6 = Tree(TreeType.apple_tree)
  44. print('{} == {}? {}'.format(id(t4), id(t5), id(t4) == id(t5)))
  45. print('{} == {}? {}'.format(id(t5), id(t6), id(t5) == id(t6)))
  46. if __name__ == '__main__':
  47. main()

8: The Model-View-Controller Pattern(mvc模式:解耦展示逻辑和业务逻辑)

When using MVC, make sure that you creating smart models (core functionality), thin controllers (functionality required for the communication between the view and the controller), and dumb views (representation and minimal processing).

MVC模式既是一种设计模式,也是软件架构模式。比如流行的django框架就是mvc(MTV)模式。Model层负责和数据库交互,View层负责展现逻辑,Controller层负责粘合Model和View层,将各个部分解耦,使代码更易扩展和维护。

  1. quotes = ('A man is not complete until he is married. Then he is finished.',
  2. 'As I said before, I never repeat myself.',
  3. 'Behind a successful man is an exhausted woman.',
  4. 'Black holes really suck...', 'Facts are stubborn things.')
  5. class QuoteModel:
  6. def get_quote(self, n):
  7. try:
  8. return quotes[n]
  9. except IndexError:
  10. return 'Not found'
  11. class QuoteTerminalView:
  12. def show(self, quote):
  13. print('And the quote is: "{}"'.format(quote))
  14. def error(self, msg):
  15. print('Error: {}'.format(msg))
  16. def select_quote(self):
  17. return input('Which quote number would you like to see? ')
  18. class QuoteTerminalController:
  19. def __init__(self):
  20. self.model = QuoteModel()
  21. self.view = QuoteTerminalView()
  22. def run(self):
  23. valid_input = False
  24. while not valid_input:
  25. n = self.view.select_quote()
  26. try:
  27. n = int(n)
  28. except ValueError:
  29. self.view.error("Incorrect index '{}'".format(n))
  30. else:
  31. valid_input = True
  32. quote = self.model.get_quote(n)
  33. self.view.show(quote)
  34. def main():
  35. controller = QuoteTerminalController()
  36. while True:
  37. controller.run()

9: The Proxy Pattern(代理模式:通过一层间接保护层实现更安全的接口访问)

在访问真正的对象之前做一些操作。有四种常用的代理类型:

  • A remote proxy.使得访问远程对象就像本地访问一样,例如网络服务器。隐藏复杂性,使得访问本地远程统一。比如ORM
  • A virtual proxy。用来实现延迟访问,比如一些需要复杂计算的对象,python里可以实现lazy_property,性能改善
  • A protection/protective proxy. 控制敏感对象的访问,加上一层保护层,实现安全控制
  • A smart(reference) proxy. 访问对象时加上一层额外操作,例如引用计数和线程安全检查。weakref.proxy()

代理模式的功能还是很强大的,先来看看使用描述符实现LazyProperty,在对象创建以后第一次访问才会真正生成

  1. class LazyProperty:
  2. """ 用描述符实现延迟加载的属性 """
  3. def __init__(self, method):
  4. self.method = method
  5. self.method_name = method.__name__
  6. def __get__(self, obj, cls):
  7. if not obj:
  8. return None
  9. value = self.method(obj)
  10. print('value {}'.format(value))
  11. setattr(obj, self.method_name, value)
  12. return value
  13. class Test:
  14. def __init__(self):
  15. self.x = 'foo'
  16. self.y = 'bar'
  17. self._resource = None
  18. @LazyProperty
  19. def resource(self): # 构造函数里没有初始化,第一次访问才会被调用
  20. print('initializing self._resource which is: {}'.format(self._resource))
  21. self._resource = tuple(range(5)) # 模拟一个耗时计算
  22. return self._resource
  23. def main():
  24. t = Test()
  25. print(t.x)
  26. print(t.y)
  27. # 访问LazyProperty, resource里的print语句只执行一次,实现了延迟加载和一次执行
  28. print(t.resource)
  29. print(t.resource)
  30. main()

再看那个用代理实现安全控制的例子,我们给SensitiveInfo里的add操作加上密钥验证,例子也很简单

  1. class SensitiveInfo:
  2. def __init__(self):
  3. self.users = ['nick', 'tom', 'ben', 'mike']
  4. def read(self):
  5. print('There are {} users: {}'.format(len(self.users), ' '.join(self.users)))
  6. def add(self, user):
  7. self.users.append(user)
  8. print('Added user {}'.format(user))
  9. class Info:
  10. '''protection proxy to SensitiveInfo'''
  11. def __init__(self):
  12. self.protected = SensitiveInfo()
  13. # 为了方便示例这里直接写死在代码里,为了安全不应该这么做
  14. self.secret = '0xdeadbeef'
  15. def read(self):
  16. self.protected.read()
  17. def add(self, user):
  18. """ 给add操作加上密钥验证,保护add操作"""
  19. sec = input('what is the secret? ')
  20. self.protected.add(user) if sec == self.secret else print("That's wrong!")
  21. def main():
  22. info = Info()
  23. while True:
  24. print('1. read list |==| 2. add user |==| 3. quit')
  25. key = input('choose option: ')
  26. if key == '1':
  27. info.read()
  28. elif key == '2':
  29. name = input('choose username: ')
  30. info.add(name)
  31. elif key == '3':
  32. exit()
  33. else:
  34. print('unknown option: {}'.format(key))
  35. main()

上面这个示例有几个缺点 1. SensitiveInfo可以被直接实例化使用,绕过Info类,可以考虑使用abc模块避免SensitiveInfo被直接实例化 2. 密钥直接写死在代码里,应该用安全性较高密钥写到配置或者环境变量里

我们使用抽象基类来修正第一个缺陷,只需要修正类代码而不用改main函数里的使用代码

  1. from abc import ABCMeta, abstractmethod
  2. class SensitiveInfo(metaclass=ABCMeta):
  3. def __init__(self):
  4. self.users = ['nick', 'tom', 'ben', 'mike']
  5. @abstractmethod
  6. def read(self):
  7. pass
  8. @abstractmethod
  9. def add(self, user):
  10. pass
  11. class Info(SensitiveInfo):
  12. '''protection proxy to SensitiveInfo'''
  13. def __init__(self):
  14. # self.protected = SensitiveInfo()
  15. super().__init__()
  16. self.secret = '0xdeadbeef' # 为了方便示例这里直接写死在代码里
  17. def read(self):
  18. print('There are {} users: {}'.format(len(self.users), ' '.join(self.users)))
  19. def add(self, user):
  20. """ 给add操作加上密钥验证,保护add操作"""
  21. sec = input('what is the secret? ')
  22. self.users.append(user) if sec == self.secret else print("That's wrong!")

10: The Chain of Responsibility Pattern (责任链模式:创建链式对象用来接收广播消息)

The Chain of Responsibility pattern is used when we want to give a chance to multiple objects to satisfy a single request, or when we don’t know which object (from a chain of objects) should process a specific request in advance.

开始介绍行为型设计模式,行为型设计模式处理对象之间的交互和算法问题。在责任连模式中,我们把消息发送给一系列对象的首个节点,对象可以选择处理消息或者向下一个对象传递,只有对消息感兴趣的节点处理。用来解耦发送者和接收者。在python里通过dynamic dispatching来实现,以一个事件驱动系统来说明:

  1. class Event:
  2. def __init__(self, name):
  3. self.name = name
  4. def __str__(self):
  5. return self.name
  6. class Widget:
  7. """Docstring for Widget. """
  8. def __init__(self, parent=None):
  9. self.parent = parent
  10. def handle(self, event):
  11. handler = 'handle_{}'.format(event)
  12. if hasattr(self, handler):
  13. method = getattr(self, handler)
  14. method(event)
  15. elif self.parent:
  16. self.parent.handle(event)
  17. elif hasattr(self, 'handle_default'):
  18. self.handle_default(event)
  19. class MainWindow(Widget):
  20. def handle_close(self, event):
  21. print('MainWindow: {}'.format(event))
  22. def handle_default(self, event):
  23. print('MainWindow: Default {}'.format(event))
  24. class SendDialog(Widget):
  25. def handle_paint(self, event):
  26. print('SendDialog: {}'.format(event))
  27. class MsgText(Widget):
  28. def handle_down(self, event):
  29. print('MsgText: {}'.format(event))
  30. def main():
  31. mw = MainWindow()
  32. sd = SendDialog(mw) # parent是mw
  33. msg = MsgText(sd)
  34. for e in ('down', 'paint', 'unhandled', 'close'):
  35. evt = Event(e)
  36. print('\nSending event -{}- to MainWindow'.format(evt))
  37. mw.handle(evt)
  38. print('Sending event -{}- to SendDialog'.format(evt))
  39. sd.handle(evt)
  40. print('Sending event -{}- to MsgText'.format(evt))
  41. msg.handle(evt)
  42. if __name__ == "__main__":
  43. main()

11: The Command Pattern(命令模式:用来给应用添加Undo操作)

命令模式帮助我们把一个操作(undo,redo,copy,paste等)封装成一个对象,通常是创建一个包含Operation所有逻辑和方法的类。 通过命令模式可以控制命令的执行时间和过程,还可以用来组织事务。 用一些文件操作类来说明命令模式的使用

  1. import os
  2. class RenameFile:
  3. def __init__(self, path_src, path_dest):
  4. """ 在init里保存一些必要信息,比如undo需要的老的和新的文件名 """
  5. self.src, self.dest = path_src, path_dest
  6. def execute(self, verbose=False):
  7. if verbose:
  8. print("[renaming '{}' to '{}']".format(self.src, self.dest))
  9. os.rename(self.src, self.dest)
  10. def undo(self, verbose=False):
  11. if verbose:
  12. print("[renaming '{}' back to '{}']".format(self.dest, self.src))
  13. os.rename(self.dest, self.src)
  14. def delete_file(path, verbose=False):
  15. if verbose:
  16. print("deleting file '{}".format(path))
  17. os.remove(path)
  18. class CreateFile:
  19. def __init__(self, path, txt='hello world\n'):
  20. self.path, self.txt = path, txt
  21. def execute(self, verbose=False):
  22. if verbose:
  23. print("[creating file '{}']".format(self.path))
  24. with open(self.path, mode='w', encoding='utf-8') as out_file:
  25. out_file.write(self.txt)
  26. def undo(self):
  27. delete_file(self.path)
  28. class ReadFile:
  29. def __init__(self, path):
  30. self.path = path
  31. def execute(self, verbose=False):
  32. if verbose:
  33. print("[reading file '{}']".format(self.path))
  34. with open(self.path, mode='r', encoding='utf-8') as in_file:
  35. print(in_file.read(), end='')
  36. def main():
  37. orig_name, new_name = 'file1', 'file2'
  38. commands = []
  39. for cmd in CreateFile(orig_name), ReadFile(orig_name), RenameFile(orig_name, new_name):
  40. commands.append(cmd)
  41. [c.execute() for c in commands]
  42. answer = input('reverse the executed commands? [y/n] ')
  43. if answer not in 'yY':
  44. print("the result is {}".format(new_name))
  45. exit()
  46. for c in reversed(commands):
  47. try:
  48. c.undo() # 执行undo
  49. except AttributeError:
  50. pass
  51. main()

12: The Interpreter Pattern(解释器模式:用来实现Domain Specific Language(DSL))

本章我们实现一个简单的控制大门Gate类的DSL。使用pyparsing来解析我们定义的控制大门的语法命令。 pyparsing自带了很多有用的函数和类帮助我们从文本中抽取需要的信息,比如我们方便地处理c++源文件中的注释:(pip install pyparsing)

  1. >>> text = '// Look out of the yard? What will we see?'
  2. >>> print pp.cppStyleComment.parseString(text)
  3. ['// Look out of the yard? What will we see?']
  4. >>> print pp.cppStyleComment.parseString('/* Author: R. J. Gumby */')
  5. ['/* Author: R. J. Gumby */']

再比如我们一句话就可以去除C++源码中的注释:

  1. from pyparsing import cppStyleComment
  2. code = """
  3. /* Hello World program */
  4. #include<stdio.h>
  5. main()
  6. {
  7. printf("Hello World"); // print hello
  8. }
  9. """
  10. print(cppStyleComment.suppress().transformString(code))

下面实现我们的控制Gate的DSL

  1. from pyparsing import Word, OneOrMore, Optional, Group, Suppress, alphanums
  2. class Gate:
  3. def __init__(self):
  4. self.is_open = False
  5. def __str__(self):
  6. return 'open' if self.is_open else 'closed'
  7. def open(self):
  8. print('opening the gate')
  9. self.is_open = True
  10. def close(self):
  11. print('closing the gate')
  12. self.is_open = False
  13. def main():
  14. # 首先定义我们的DSL格式,我们这里最简单的控制语法就是 "open -> gate"
  15. word = Word(alphanums)
  16. command = Group(OneOrMore(word))
  17. token = Suppress("->")
  18. device = Group(OneOrMore(word))
  19. argument = Group(OneOrMore(word))
  20. event = command + token + device + Optional(token + argument)
  21. gate = Gate()
  22. cmds = ['open -> gate', 'close -> gate'] # 两个自定义的命令
  23. open_actions = {'gate': gate.open}
  24. close_actions = {'gate': gate.close}
  25. for cmd in cmds:
  26. print(event.parseString(cmd)) # [['open'], ['gate']]
  27. cmd, dev = event.parseString(cmd)
  28. cmd_str, dev_str = ' '.join(cmd), ' '.join(dev)
  29. print(cmd_str, dev_str)
  30. if 'open' in cmd_str:
  31. open_actions[dev_str]()
  32. elif 'close' in cmd_str:
  33. close_actions[dev_str]()
  34. if __name__ == "__main__":
  35. main()

这样就实现了一个简单的大门控制语言,不过功能很弱。


13: The Observer Pattern(发布订阅模式:用来处理多个对象之间的发布订阅问题)

如果用过blinker库或者redis的pub,sub,对发布订阅应该会比较熟悉。该模式用在当一个对象的状态变更需要通知其他很多对象的时候,比如rss订阅或者在社交网站上订阅某个频道的更新。事件驱动系统也是一种发布订阅模式,事件作为发布者,监听器作为订阅者,只不过这里多个事件监听器可以监听同一个事件。 我们这里实现一个”Data Formatter”来解释发布订阅模式,一种数据可以有多个格式化Formatter,当数据更新的时候,会通知所有的Formatter格式化新的数据。使用继承来实现。

  1. class Publisher:
  2. def __init__(self):
  3. self.observers = []
  4. def add(self, observer):
  5. if observer not in self.observers:
  6. self.observers.append(observer)
  7. else:
  8. print('Failed to add : {}').format(observer)
  9. def remove(self, observer):
  10. try:
  11. self.observers.remove(observer)
  12. except ValueError:
  13. print('Failed to remove : {}').format(observer)
  14. def notify(self):
  15. [o.notify_by(self) for o in self.observers]
  16. class DefaultFormatter(Publisher):
  17. def __init__(self, name):
  18. super().__init__()
  19. self.name = name
  20. self._data = 0
  21. def __str__(self):
  22. return "{}: '{}' has data = {}".format(
  23. type(self).__name__, self.name, self._data)
  24. @property
  25. def data(self):
  26. return self._data
  27. @data.setter
  28. def data(self, new_value):
  29. try:
  30. self._data = int(new_value)
  31. except ValueError as e:
  32. print('Error: {}'.format(e))
  33. else:
  34. self.notify() # data 在被合法赋值以后会执行notify
  35. class HexFormatter:
  36. """ 订阅者 """
  37. def notify_by(self, publisher):
  38. print("{}: '{}' has now hex data = {}".format(
  39. type(self).__name__, publisher.name, hex(publisher.data)))
  40. class BinaryFormatter:
  41. """ 订阅者 """
  42. def notify_by(self, publisher):
  43. print("{}: '{}' has now bin data = {}".format(
  44. type(self).__name__, publisher.name, bin(publisher.data)))
  45. if __name__ == "__main__":
  46. df = DefaultFormatter('test1')
  47. print(df)
  48. print()
  49. hf = HexFormatter()
  50. df.add(hf)
  51. df.data = 3
  52. print(df)
  53. print()
  54. bf = BinaryFormatter()
  55. df.add(bf)
  56. df.data = 21
  57. print(df)

14: The State Pattern(状态模式:实现有限状态机)

A state machine is an abstract machine that has two key components: states and transitions. A state is the current (active) status of a system. A transition is the switch from one state to another. A state meachine has only one active state at a specific point in the time.

我们通过实现操作系统中进程的生命周期来演示状态模式的使用:

  1. # 先装下pip3 install state_machine
  2. from state_machine import (
  3. acts_as_state_machine, State, Event, before, after, InvalidStateTransition
  4. )
  5. @acts_as_state_machine
  6. class Process:
  7. # 先来定义状态机的状态 states
  8. created = State(initial=True) # 初始状态
  9. waiting = State()
  10. running = State()
  11. terminated = State()
  12. blocked = State()
  13. swapped_out_waiting = State()
  14. swapped_out_blocked = State()
  15. # 再定义状态机的转移 transitions
  16. wait = Event(from_states=(created, running, blocked,
  17. swapped_out_waiting), to_state=waiting)
  18. run = Event(from_states=waiting, to_state=running)
  19. terminate = Event(from_states=running, to_state=terminated)
  20. block = Event(from_states=(running, swapped_out_blocked),
  21. to_state=blocked)
  22. swap_wait = Event(from_states=waiting, to_state=swapped_out_waiting)
  23. swap_block = Event(from_states=blocked, to_state=swapped_out_blocked)
  24. def __init__(self, name):
  25. self.name = name
  26. # The state_machine module provides us with the @before and @after
  27. # decorators that can be used to execute actions before or after a
  28. # transition occurs, respectfully.
  29. @after('wait')
  30. def wait_info(self):
  31. print('{} entered waiting mode'.format(self.name))
  32. @after('run')
  33. def run_info(self):
  34. print('{} is running'.format(self.name))
  35. @before('terminate')
  36. def terminate_info(self):
  37. print('{} terminated'.format(self.name))
  38. @after('block')
  39. def block_info(self):
  40. print('{} is blocked'.format(self.name))
  41. @after('swap_wait')
  42. def swap_wait_info(self):
  43. print('{} is swapped out and waiting'.format(self.name))
  44. @after('swap_block')
  45. def swap_block_info(self):
  46. print('{} is swapped out and blocked'.format(self.name))
  47. def transition(process, event, event_name):
  48. """
  49. Args:
  50. process (Process obj):
  51. event (Event obj): wait, run, terminate...
  52. event_name (str): name of event
  53. """
  54. try:
  55. event()
  56. except InvalidStateTransition:
  57. print('Error: transition of {} from {} to {} failed'.format(
  58. process.name, process.current_state, event_name))
  59. def state_info(process):
  60. """ 当前状态机的状态 """
  61. print('state of {}: {}'.format(process.name, process.current_state))
  62. if __name__ == "__main__":
  63. RUNNING = 'running'
  64. WAITING = 'waiting'
  65. BLOCKED = 'blocked'
  66. TERMINATED = 'terminated'
  67. p1, p2 = Process('process1'), Process('process2')
  68. [state_info(p) for p in (p1, p2)]
  69. print()
  70. transition(p1, p1.wait, WAITING)
  71. transition(p2, p2.terminate, TERMINATED)
  72. [state_info(p) for p in (p1, p2)]
  73. print()
  74. transition(p1, p1.run, RUNNING)
  75. transition(p2, p2.wait, WAITING)
  76. [state_info(p) for p in (p1, p2)]
  77. print()
  78. transition(p2, p2.run, RUNNING)
  79. [state_info(p) for p in (p1, p2)]
  80. print()
  81. [transition(p, p.block, BLOCKED) for p in (p1, p2)]
  82. [state_info(p) for p in (p1, p2)]
  83. print()
  84. [transition(p, p.terminate, TERMINATED) for p in (p1, p2)]
  85. [state_info(p) for p in (p1, p2)]

15: The Strategy Pattern(策略模式:动态选择算法策略)

现实中往往解决问题的方式不止一种,我们可能需要根据问题的特征选择最优的实现策略,以排序算法为例子,挑选一个合适的排序算法的时候,需要考虑待排序数组的以下特征:

  • 元素个数。算法输入规模,大部分排序算法在输入规模很小的时候效率相差不大,只有一部分nlogn平均时间复杂度的适合排序大规模。
  • 最好/平均/最坏时间复杂度.这个往往是挑选排序算法时候优先考虑的。
  • 空间复杂度。是不是原地排序(inplace),需要额外的空间吗?在内存限制苛刻的时候就需要考虑
  • 稳定性。排序算法是稳定的吗?稳定是指相同大小的值排序后保持相对顺序。
  • 实现复杂度。算法是否容易实现,其他大致相同的情况下,优先考虑易维护的代码。

策略模式允许我们根据待处理数据的特征灵活选用当前特征下最优的实现,比如常见库的排序算法一般都是混合了多种排序算法的实现,python使用的是Tim Peters在2002年设计的结合了合并排序和插入排序的Timsort. 函数在python里是一等公民,可以简化策略模式的实现。

  1. def f1(seq):
  2. pass
  3. def f2(seq):
  4. pass
  5. def f(seq):
  6. if len(seq) >= threshold_value: # 大于某个阈值
  7. f1(seq) # 在数量较多时候具有良好的效率
  8. else:
  9. f2(seq)

16: The Template Pattern(模板模式:抽象出算法公共部分从而实现代码复用)

Don’t repeat yourself.

模板模式中,我们可以把代码中重复的部分抽出来作为一个新的函数,把可变的部分作为函数参数,从而消除代码冗余。实际上这种模式在代码重构的时候是经常使用的 ,使用一个有意思的例子来说明下,请安装pip install cowpy,真有人闲的*疼写这个玩意

  1. from cowpy import cow
  2. def dots_style(msg):
  3. msg = msg.capitalize()
  4. msg = '.' * 10 + msg + '.' * 10
  5. return msg
  6. def admire_style(msg):
  7. msg = msg.upper()
  8. return '!'.join(msg)
  9. def cow_style(msg):
  10. msg = cow.milk_random_cow(msg)
  11. return msg
  12. def generate_banner(msg, style=dots_style):
  13. print('-- start of banner --')
  14. print(style(msg))
  15. print('-- end of banner --\n\n')
  16. def main():
  17. msg = 'happy coding'
  18. [generate_banner(msg, style) for style in (dots_style, admire_style,
  19. cow_style)]
  20. if __name__ == "__main__":
  21. main()
  22. """
  23. -- start of banner --
  24. ..........Happy coding..........
  25. -- end of banner --
  26. -- start of banner --
  27. H!A!P!P!Y! !C!O!D!I!N!G
  28. -- end of banner --
  29. -- start of banner --
  30. ______________
  31. < happy coding >
  32. --------------
  33. o
  34. o
  35. ^__^ /
  36. (**)\_______/ _________
  37. (__)\ )=( ____|_ \_____
  38. U ||----w | \ \ \_____ |
  39. || || || ||
  40. -- end of banner --
  41. """

单例模式: 使得一个类最多生成一个实例。

Design ptterns are discoverd, not invented. - Alex Martelli

很奇怪,本书讲完了都没有讲到单例模式。python的单例模式有各种实现,元类、装饰器等,但是还有一种说法:

I don’t really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can’t protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.

也就是说,实际上,python中,如果我们只用一个实例,直接这么写就行

  1. # some module.py
  2. class SingletonClass:
  3. pass
  4. # 在别处我们想用这个实例都直接使用 module.single_instance 这个实例就好。
  5. # 这是最简单也是最直观的一种方式,嗯,直接导入这个实例用,而不是导入class,简单粗暴
  6. single_instance = SingletonClass()

Is there a simple, elegant way to define singletons in Python? [closed]

其他实现:

  1. # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
  2. class BaseClass:
  3. pass
  4. # 装饰器实现
  5. def singleton(class_):
  6. instances = {}
  7. def getinstance(*args, **kwargs):
  8. if class_ not in instances:
  9. instances[class_] = class_(*args, **kwargs)
  10. return instances[class_]
  11. return getinstance
  12. @singleton
  13. class MyClass(BaseClass):
  14. pass
  15. class Singleton(object):
  16. _instance = None
  17. def __new__(class_, *args, **kwargs):
  18. if not isinstance(class_._instance, class_):
  19. class_._instance = object.__new__(class_, *args, **kwargs)
  20. return class_._instance
  21. class MyClass(Singleton, BaseClass):
  22. pass
  23. # 元类实现
  24. class Singleton(type):
  25. _instances = {}
  26. def __call__(cls, *args, **kwargs):
  27. if cls not in cls._instances:
  28. cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
  29. return cls._instances[cls]
  30. # Python2
  31. class MyClass(BaseClass):
  32. __metaclass__ = Singleton
  33. # Python3
  34. class MyClass(BaseClass, metaclass=Singleton):
  35. pass

面向过程与面向对象

设计模式讲完了,来看看python中OOP的相关东西。

  • 过程式: 基本都是一个个函数(function)来实现功能,你给我一些参数,我对参数做出各种操作,返回需要的结果。
  • 面向对象:把资源抽象成一个类,数据(data)和方法(method)的集合。在构造函数中进行数据属性的初始化,在方法中进行对象数据的各种操作。实际在python里,一切皆对象。

哪种方式更好这个我暂时没有定论,编程规范也不会说强制你使用哪种风格。编码中往往没有绝对正确的,只有相对更优的,如果不好定论,那就一致,易读,易用,易维护的风格优先。一般来说,能用函数实现的优先使用函数,相比类更简单易维护。如果多个过程共享一些状态(操作+数据),这时候使用类就比较适合。使用类的时候尽量保持继承层级简单,如果同样可以完成功能,优先使用组合而非继承。


python中的抽象基类

在python中我们可以使用内置的abc(abstract base class)模块来实现抽象基类。什么时候需要一个抽象基类呢?

  • 抽象基类是没法被实例化的。
  • 抽象基类中定义抽象方法强制子类去实现,没有实现抽象方法的子类也无法实例化。
  1. # 为了实现这两个特性,我们可以这么写
  2. class Base:
  3. def foo(self):
  4. raise NotImplementedError()
  5. def bar(self):
  6. raise NotImplementedError()
  7. class Concrete(Base):
  8. def foo(self):
  9. return 'foo() called'
  10. # Oh no, we forgot to override bar()...
  11. # def bar(self):
  12. # return "bar() called"

但是这么写依然可以实例化Base,python2.6以后引入了abc模块帮助我们实现这个功能。

  1. from abc import ABCMeta, abstractmethod
  2. class Base(metaclass=ABCMeta):
  3. @abstractmethod
  4. def foo(self):
  5. pass
  6. @abstractmethod
  7. def bar(self):
  8. pass
  9. class Concrete(Base):
  10. def foo(self):
  11. pass
  12. # We forget to declare bar() again...

使用这种方式如果没有在子类里实现bar方法你是没有办法实例化子类的。合理使用抽象基类定义明确的接口。另外应该优先使用collections定义的抽象基类,比如要实现一个容器我们可以继承 collections.Container


python中的Mixin

Mixin是为了给一个类扩充功能用的,它也没法被实例化。我们可以在Mixin类里实现一些方法给类扩充功能,合理使用mixin也能避免复杂的继承关系。你可能会问了,那为啥不直接写在类里头,比如用@staticmethod方法(我就有这个疑问)?我的理解是这样的,为了『高内聚』。如果你用过pylint检测代码,你会发现你在写类的一个方法时,如果在写一个method时没有使用到任何self里的东西,pylint会给提示『R0201 Method could be a function [pylint]』,意思是这个方法可以可以单独写成一个函数,不必要写在类里。也就是说,只有一个类里实现的方法都是使用了self里的数据时才能成为高内聚的(我不知道我这样理解对不对)。例子:flask_login插件有个UserMixin给定义的用户类实现登录功能。关于多重继承和 mixin 在 Ruby 之父的书《松本行弘的程序世界》中有不错的科普。