命令模式

C#

using System;using System.Collections.Generic;namespace CommandPattern{
    public interface ICommand
    {
        void Execute();
    }

    /* The Invoker class */
    public class Switch
    {
        private List<ICommand> _commands = new List<ICommand>();

        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 > 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.");
            }
        }
    }}

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<Command> history = new ArrayList<Command>();

   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.");
      }
   }}

Python

1 class Switch(object): 2     """The INVOKER class""" 3     def __init__(self, flip_up_cmd, flip_down_cmd): 4         self.flip_up = flip_up_cmd 5         self.flip_down = flip_down_cmd 6  7 class Light(object): 8     """The RECEIVER class""" 9     def turn_on(self):10         print("The light is on")11     def turn_off(self):12         print("The light is off")13 14 class LightSwitch(object):15     """The CLIENT class"""16     def __init__(self):17         lamp = Light()18         self._switch = Switch(lamp.turn_on, lamp.turn_off)19 20     def switch(self, cmd):21         cmd = cmd.strip().upper()22         if cmd == "ON":23             self._switch.flip_up()24         elif cmd == "OFF":25             self._switch.flip_down()26         else:27             print("Argument 'ON' or 'OFF' is required.")28 29 # Execute if this file is run as a script and not imported as a module30 if __name__ == "__main__":31     light_switch = LightSwitch()32     print("Switch ON test.")33     light_switch.switch("ON")34     print("Switch OFF test.")35     light_switch.switch("OFF")36     print("Invalid Command test.")37     light_switch.switch("****")

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" => s.storeAndExecute(switchUp)
            case "OFF" => s.storeAndExecute(switchDown)
            case _ => println("Argument \"ON\" or \"OFF\" is required.")
         }
      } catch {
         case e: Exception => println("Arguments required.")
      }
   }}

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);