命令模式

在物件导向程式设计的范畴中，命令模式（英语：Command pattern）是一种设计模式，它尝试以物件来代表实际行动。
概述.
命令物件可以把行动(action) 及其参数封装起来，于是这些行动可以被：
这些都是现代大型应用程式所必须的功能，即「复原」及「重复」。除此之外，可以用命令模式来实作的功能例子还有：交易行为、进度列、精灵、使用者介面按钮及功能表项目、执行绪pool和巨集收录等等。
结构.
在上面的UML类图中，codice_1类不直接实现一个请求。codice_1转而提及到codice_3接口，通过它来办理一个请求（codice_4），这使得codice_1独立于这些请求的办理者。codice_6类实现了codice_3接口，它在一个接收者（codice_8）上施行一个动作。此外，客户codice_9创建具体命令类比如codice_6的对象并设置它的接收者。
UML序列图展示了运行时交互：codice_1对象调用codice_12于codice_6对象之上。codice_6调用codice_15在一个codice_16对象之上，它办理这个请求。
范例.
C++.
下面是C++例子：
class ICommand {
public:
 virtual void Execute() = 0;
class Switcher {
private:
 std::vector&lt;ICommand *&gt; _commands;
public:
 void StoreAndExecute(ICommand *command) {
 if (command){
 _commands.push_back(command);
 command-&gt;Execute();
class Light {
public:
 void TurnOn() {
 std::cout«"The light is on."«std::endl;
 void TurnOff() {
 std::cout « "The light is off." « std::endl;
};
/* The Command for turning on the light - ConcreteCommand #1 */
class FlipUpCommand : public ICommand {
private:
 Light *_light;
public:
 FlipUpCommand(Light *light) {
 _light = light;
 void Execute() {
 _light-&gt;TurnOn();
};
/* The Command for turning off the light - ConcreteCommand #2 */
class FlipDownCommand : public ICommand {
private:
 Light *_light;
public:
 FlipDownCommand(Light *light) {
 _light = light;
 void Execute() {
 _light-&gt;TurnOff();
};
int main() {
 Light *light = new Light();
 ICommand *switchOn = dynamic_cast&lt;ICommand *&gt;(new FlipUpCommand(light));
 ICommand *switchDown = dynamic_cast&lt;ICommand *&gt;(new FlipDownCommand(light));
 Switcher *switcher = new Switcher();
 switcher-&gt;StoreAndExecute(switchOn);
 switcher-&gt;StoreAndExecute(switchDown);
 delete switcher;
 delete switchOn;
 delete switchDown;
 delete light;
Java.
下面是Java例子：
import java.util.List;
import java.util.ArrayList;
/* The Command interface */
public interface Command {
 void execute();
/* The Invoker class */
public class Switch {
 private List&lt;Command&gt; history = new ArrayList&lt;Command&gt;();
 public Switch() {
 public void storeAndExecute(Command cmd) {
 this.history.add(cmd); // optional 
 cmd.execute(); 
/* The Receiver class */
public class Light {
 public Light() {
 public void turnOn() {
 System.out.println("The light is on");
 public void turnOff() {
 System.out.println("The light is off");
/* The Command for turning on the light - ConcreteCommand #1 */
public class FlipUpCommand implements Command {
 private Light theLight;
 public FlipUpCommand(Light light) {
 this.theLight = light;
 public void execute(){
 theLight.turnOn();
/* The Command for turning off the light - ConcreteCommand #2 */
public class FlipDownCommand implements Command {
 private Light theLight;
 public FlipDownCommand(Light light) {
 this.theLight = light;
 public void execute() {
 theLight.turnOff();
/* The test class or client */
public class PressSwitch {
 public static void main(String[] args){
 Light lamp = new Light();
 Command switchUp = new FlipUpCommand(lamp);
 Command switchDown = new FlipDownCommand(lamp);
 Switch mySwitch = new Switch();
 try {
 if ("ON".equalsIgnoreCase(args[0])) {
 mySwitch.storeAndExecute(switchUp);
 else if ("OFF".equalsIgnoreCase(args[0])) {
 mySwitch.storeAndExecute(switchDown);
 else {
 System.out.println("Argument \"ON\" or \"OFF\" is required.");
 } catch (Exception e) {
 System.out.println("Arguments required.");
C#.
下面是C#例子：
using System;
using System.Collections.Generic;
namespace CommandPattern {
 public interface ICommand {
 void Execute();
 /* The Invoker class */
 public class Switch {
 private List&lt;ICommand&gt; _commands = new List&lt;ICommand&gt;();
 public void StoreAndExecute(ICommand command) {
 _commands.Add(command);
 command.Execute();
 /* The Receiver class */
 public class Light {
 public void TurnOn() {
 Console.WriteLine("The light is on");
 public void TurnOff() {
 Console.WriteLine("The light is off");
 /* The Command for turning on the light - ConcreteCommand #1 */
 public class FlipUpCommand : ICommand {
 private Light _light;
 public FlipUpCommand(Light light) {
 _light = light;
 public void Execute() {
 _light.TurnOn();
 /* The Command for turning off the light - ConcreteCommand #2 */
 public class FlipDownCommand : ICommand {
 private Light _light;
 public FlipDownCommand(Light light) {
 _light = light;
 public void Execute() {
 _light.TurnOff();
 /* The test class or client */
 internal class Program {
 public static void Main(string[] args) {
 Light lamp = new Light();
 ICommand switchUp = new FlipUpCommand(lamp);
 ICommand switchDown = new FlipDownCommand(lamp);
 Switch s = new Switch();
 string arg = args.Length &gt; 0 ? args[0].ToUpper() : null;
 if (arg == "ON") {
 s.StoreAndExecute(switchUp);
 else if (arg == "OFF") {
 s.StoreAndExecute(switchDown);
 else {
 Console.WriteLine("Argument \"ON\" or \"OFF\" is required.");
Python.
下面是Python例子：
from abc import ABC, abstractmethod
class Command(ABC):
 @abstractmethod
 def execute(self): pass
class Light():
 def turn_on(self):
 print("The light is on")
 def turn_off(self):
 print("The light is off") 
class FlipUpCommand(Command):
 def __init__(self, light):
 self.name = "FlipUpCommand"
 self.__light = light
 def execute(self):
 self.__light.turn_on()
class FlipDownCommand(Command):
 def __init__(self, light):
 self.name = "FlipDownCommand"
 self.__light = light
 def execute(self):
 self.__light.turn_off()
class Switch():
 def __init__(self,):
 self.history = [] 
 def invoke(self, cmd):
 assert isinstance(cmd, Command)
 self.history += [cmd.name]
 cmd.execute()
class PressSwitch():
 def __init__(self):
 lamp = Light()
 self.__switch_up = FlipUpCommand(lamp)
 self.__switch_down = FlipDownCommand(lamp)
 self.__switch = Switch() 
 def __call__(self, cmd):
 cmd = cmd.strip().upper()
 if cmd == "ON":
 self.__switch.invoke(self.__switch_up)
 elif cmd == "OFF":
 self.__switch.invoke(self.__switch_down)
 else:
 print("Argument 'On' or 'Off' is required.")
其执行：
»&gt; press_switch = PressSwitch()
»&gt; press_switch("On")
The light is on
»&gt; press_switch("Off")
The light is off
»&gt; press_switch("ThirdState")
Argument 'On' or 'Off' is required.
Scala.
下面是Scala例子：
/* The Command interface */
trait Command {
 def execute()
 
/* The Invoker class */
class Switch {
 private var history: List[Command] = Nil
 def storeAndExecute(cmd: Command) {
 cmd.execute()
 this.history :+= cmd
/* The Receiver class */
class Light {
 def turnOn() = println("The light is on")
 def turnOff() = println("The light is off")
 
/* The Command for turning on the light - ConcreteCommand #1 */
class FlipUpCommand(theLight: Light) extends Command {
 def execute() = theLight.turnOn()
 
/* The Command for turning off the light - ConcreteCommand #2 */
class FlipDownCommand(theLight: Light) extends Command {
 def execute() = theLight.turnOff()
 
/* The test class or client */
object PressSwitch {
 def main(args: Array[String]) {
 val lamp = new Light()
 val switchUp = new FlipUpCommand(lamp)
 val switchDown = new FlipDownCommand(lamp)
 val s = new Switch()
 try {
 args(0).toUpperCase match {
 case "ON" =&gt; s.storeAndExecute(switchUp)
 case "OFF" =&gt; s.storeAndExecute(switchDown)
 case _ =&gt; println("Argument \"ON\" or \"OFF\" is required.")
 } catch {
 case e: Exception =&gt; println("Arguments required.")
Javascript.
下面是Javascript例子：
/* The Invoker function */
var Switch = function(){
 var _commands = [];
 this.storeAndExecute = function(command){
 _commands.push(command);
 command.execute();
/* The Receiver function */
var Light = function(){
 this.turnOn = function(){ console.log ('turn on')};
 this.turnOff = function(){ console.log ('turn off') };
/* The Command for turning on the light - ConcreteCommand #1 */
var FlipUpCommand = function(light){
 this.execute = light.turnOn;
/* The Command for turning off the light - ConcreteCommand #2 */
var FlipDownCommand = function(light){
 this.execute = light.turnOff;
var light = new Light();
var switchUp = new FlipUpCommand(light);
var switchDown = new FlipDownCommand(light);
var s = new Switch();
s.storeAndExecute(switchUp);
s.storeAndExecute(switchDown);