github地址:https://github.com/cheesezh/python_design_patternspython
用程序模拟,顾客直接向烤串师傅提需求。git
class Barbecuer(): def bake_mutton(self): print("烤羊肉串") def bake_chicken_wing(self): print("烤鸡翅") def main(): boy = Barbecuer() boy.bake_mutton() boy.bake_mutton() boy.bake_mutton() boy.bake_chicken_wing() boy.bake_mutton() boy.bake_mutton() boy.bake_chicken_wing() main()
烤羊肉串 烤羊肉串 烤羊肉串 烤鸡翅 烤羊肉串 烤羊肉串 烤鸡翅
客户端程序与“烤串师傅”紧耦合,尽管简单,可是极为僵化,当顾客多了,请求多了,就容易乱了。github
用程序模拟,顾客向服务员提需求,服务员再告知烤串师傅。app
from abc import ABCMeta, abstractmethod class Command(): """ 抽象命令类 """ __metaclass__ = ABCMeta # 须要肯定一个命令接收者 def __init__(self, receiver): self.receiver = receiver @abstractmethod def excute_command(self): pass class BakeMuttonCommand(Command): """ 具体命令类 """ def excute_command(self): self.receiver.bake_mutton() def to_string(self): return "烤羊肉串" class BakeChickenWingCommand(Command): """ 具体命令类 """ def excute_command(self): self.receiver.bake_chicken_wing() def to_string(self): return "烤鸡翅" class Waiter(): """ 服务员类, 不用管顾客的烤串要怎么烤,对于服务员来讲,都看成命令记录下来就行,而后通知“烤串师傅”执行便可。 """ def __init__(self): self.orders = [] def set_order(self, cmd): if cmd.to_string() == "烤鸡翅": print("鸡翅没了,换点其余的吧") else: self.orders.append(cmd) print("增长订单:", cmd.to_string()) def cancel_order(self, cmd): self.orders.remove(cmd) print("取消订单:", cmd.to_string()) def notify(self): for cmd in self.orders: cmd.excute_command() def main(): # 开店准备 boy = Barbecuer() bake_mutton_1 = BakeMuttonCommand(boy) bake_mutton_2 = BakeMuttonCommand(boy) bake_chicken_wing = BakeChickenWingCommand(boy) girl = Waiter() # 开门营业 girl.set_order(bake_mutton_1) girl.set_order(bake_mutton_2) girl.set_order(bake_chicken_wing) # 开始制做 girl.notify() main()
增长订单: 烤羊肉串 增长订单: 烤羊肉串 鸡翅没了,换点其余的吧 烤羊肉串 烤羊肉串
命令模式,讲一个请求封装成一个对象,从而使你可用不一样的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销操做。[DP]设计
主要包括如下几种类:日志
命令模式的优势:code