Command模式只是封装了一个没有任何变量的函数.
public interface CommandEngine { void AddCommand(Command cmd); } public class RTCEngine : CommandEngine { private List<Command> Commands; public RTCEngine() { this.Commands = new List<Command>(); } public void AddCommand(Command cmd) { this.Commands.Add(cmd); } /// <summary> /// 执行Command队列中的所有命令,直至队列中不再含有任何的Command. /// </summary> public void Do() { while (this.Commands.Count > 0) { var cmd = Commands.First(); this.Commands.Remove(cmd); cmd.Excute(); } } }
1 public interface Command 2 { 3 void Excute(); 4 } 5 6 7 8 public class SleepCommand : Command 9 { 10 private long sleepTime; 11 12 private CommandEngine engine; 13 private Command callBack; 14 15 private bool start; 16 private long startTime; 17 18 public SleepCommand(long timeout, CommandEngine engine, Command callBack) 19 { 20 this.sleepTime = timeout; 21 this.engine = engine; 22 this.callBack = callBack; 23 24 this.start = false; 25 } 26 27 #region Command Members 28 29 /// <summary> 30 /// 执行,根据条件克隆自己或者添加CallBack命令到Engine中去. 31 /// </summary> 32 public void Excute() 33 { 34 long time = System.DateTime.Now.Ticks; 35 36 //如果还未启动,那么启动自身,同时将自己添加到Engine队列末尾. 37 if (!start) 38 { 39 this.start = true; 40 this.startTime = time; 41 engine.AddCommand(this); 42 } 43 //如果还没到唤醒时间,那么添加自己到Engine的队列末尾. 44 if (time - startTime < sleepTime) 45 { 46 engine.AddCommand(this); 47 } 48 else 49 { 50 //已经到唤醒时间,将CallBack命令添加到Engine的队列末尾. 51 engine.AddCommand(callBack); 52 } 53 } 54 55 #endregion 56 }
总结. Command模式具有极其的简洁性.但可以用于DB的Transaction操作,设备控制,多线程核心,GUI的do/undo管理.
其有不符合OO范式的味道.对函数的关注超过了类.
[Agile Software Development(Principles,Patterns,and Pracitices)]
原文:http://www.cnblogs.com/RobynHan/p/3729294.html