命令模式 CommandPattern

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

调用代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值