当前位置: 代码迷 >> 综合 >> Design Patterns - Command
  详细解决方案

Design Patterns - Command

热度:72   发布时间:2023-10-21 05:00:57.0

Command(命令) — 对象行为型模式

命令模式是利用类来实现对命令函数的封装,实现命令调用者和命令接收者之间的解耦。

适用场景

  1. 系统需要将请求调用者和请求接收者解耦,使得调用者和接收者不直接交互。
  2. 系统需要在不同的时间指定请求,将请求排队和执行请求。
  3. 系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作。
  4. 系统需要将一组操作组合在一起,即支持宏命令。

UML图

Design Patterns - Command

效果

  1. 解耦请求调用者和请求接收者。
  2. Command 是头等的对象。他们可像其他的对象一样被操作和扩展。
  3. 可以将多个命令装配成一个组合命令。
  4. 增加新的 Command 很容易,因为无须改变已有的类。

实现

import abcclass 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.abstractmethoddef execute(self):passclass StartCommand(Command):"""start命令类,对命令接收者类中start方法的封装"""def __init__(self, receiver):self.receiver = receiverdef execute(self):self.receiver.start()class StopCommand(Command):"""stop命令类,对命令接收者类中stop方法的封装"""def __init__(self, receiver):self.receiver = receiverdef execute(self):self.receiver.stop()class Client(object):"""调用命令的客户端"""def __init__(self, command):self.command = commanddef command_do(self):self.command.execute()

client


if __name__ == '__main__':receiver = Receiver()start_command = StartCommand(receiver)client = Client(start_command)client.command_do()# 可以直接更换命令,如下,把start命令,换成stop命令stop_command = StopCommand(receiver)client.command = stop_commandclient.command_do()
""" output: execute start command execute stop command """
  相关解决方案