命令模式是利用类来实现对命令函数的封装,实现命令调用者和命令接收者之间的解耦,命令模式具体包括三部分:
1 命令调用者(客户端,调用命令的函数或者类)
2 命令(对命令接收者命令函数的封装)
3 命令接收者(真正执行命令的地方,实现了众多命令函数)
三者的关系如下图
具体代码实现如下
import abc
class Receiver(object):
'''
命令接收者,正在执行命令的地方,实现了众多命令函数
'''
def start(self):
print('execute start command')
def stop(self):
print('execute stop command')
def suspend(self):
print('execute suspend command')
def play(self):
print('execute play command')
class Command(object):
"""
command抽象方法,子类必须要实现execute方法
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def execute(sel