using System; using System.Collections; class Controller { ArrayList CommandList; public Controller() { CommandList = new ArrayList(); } public void addCommand(ICommand command) { CommandList.Add(command); } public void delCommand(ICommand command) { } public void ExecuteCommand(int commandindex) { if (commandindex < 0 || commandindex > CommandList.Count - 1) return; ((ICommand)CommandList[commandindex]).Execute(); } }
命令对象的调用者
interface ICommand { void Execute(); }
命令对象接口
using System; class Computer:ICommand { public Computer() { } public void Open() { Console.WriteLine("The Computer is Open now!"); } public void Close() { Console.WriteLine("The Computer is Close now!"); } #region ICommand 成员 public void Execute() { Open(); } #endregion }
命令对象接口的实现A
using System; class Light:ICommand { public Light() { } public void On() { Console.WriteLine("The light is on now!"); } public void Off() { Console.WriteLine("The light is off now!"); } #region ICommand 成员 public void Execute() { On(); } #endregion }
命令对象的实现B
using System; class Television:ICommand { public Television() { } public void Open() { Console.WriteLine("The television is open now!"); } public void Close() { Console.WriteLine("The television is close now!"); } #region ICommand 成员 public void Execute() { Open(); } #endregion }
命令对象的实现C
using System; using System.Collections.Generic; using System.Text; namespace CommandPattern { class Program { static void Main(string[] args) { ICommand cmdLight = new Light(); ICommand cmdComputer = new Computer(); ICommand cmdTelevision = new Television(); Controller controller = new Controller(); controller.addCommand(cmdLight); controller.addCommand(cmdComputer); controller.addCommand(cmdTelevision); controller.ExecuteCommand(0); controller.ExecuteCommand(1); controller.ExecuteCommand(2); Console.Read(); } } }
调用代码