我的理解: 命令池(采用堆或栈皆可)维护着一组命令集合。 只要这些命令实现同个命令接口或者命令抽象类,就能够被命令池依次执行。 class App { static void Main() { //命令模式:将无论哪个实例的方法抽象成对应的命令放入命令池。命令池会自动执行。 Printer printer = new Printer(); Scanner scanner = new Scanner(); PrintCommand pc = new PrintCommand(printer); ScanCommand sc = new ScanCommand(scanner); CommandQueue.Instance.Enquee(pc); CommandQueue.Instance.Enquee(sc); }} // ICommand命令池,计时器每过一段时间取出一个命令执行 public class CommandQueue : Queue < ICommand > { 单例#region 单例 private static class CommandQueueInstance { public static readonly CommandQueue Instance = new CommandQueue(); } public static CommandQueue Instance { get { return CommandQueueInstance.Instance; } } #endregion private Timer _t; private CommandQueu() { _t = new Timer(new TimerCallback(Execute), null, 5000, 200); } private void Execute(object obj) { if (this.Count > 0) { ICommand cmd = this.Dequeue(); cmd.Execute(); } }} // 所有命令的抽象,这里使用接口比较好 public interface ICommand { void Execute();} // 打印机打印的命令 public class PrintCommand : ICommand { private Printer _printer; public PrintCommand( Printer printer) { _printer = printer; } public virtual void Execute() { _printer.Print(); }} // 扫描仪扫描的命令 public class ScanCommand : ICommand { private Scanner _scanner; public ScanCommand(Scanner scanner) { _scanner = scanner; } public virtual void Execute() { _scanner.Scan(); }} // 打印机提供打印方法 public class Printer { public void Print() { Console.WriteLine("Print."); }} // 扫描仪提供扫描方法 public class Scanner { public void Scan() { Console.WriteLine("Scan."); }} 转载于:https://www.cnblogs.com/yurichou/archive/2007/08/13/854151.html