原文地址http://www.cnblogs.com/zhili/p/CommandPattern.html
class Program { static void Main(string[] args) { //实现命令的人 执行命令的人,下命令的人 Receiver receiver = new Receiver(); Command command = new ConcreateCommand(receiver); Invoke invoke = new Invoke(command); //下命令 invoke.ExecuteCommand(); Console.Read(); } } //教官 负责调用命令执行任务 public class Invoke { public Command command; public Invoke(Command command) { this.command = command; } public void ExecuteCommand() { command.Action();//跑步 command.ActionTiao();//跳舞 } } //命令抽象类 public abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } //命令执行方法 public abstract void Action(); //加命令 进行扩展 跳舞 --------------扩展 跳舞 public abstract void ActionTiao(); } public class ConcreateCommand : Command { public ConcreateCommand(Receiver receiver):base(receiver) { } //执行命令 public override void Action() { receiver.Run1000Meters(); } //跳舞 public override void ActionTiao() { receiver.TiaoWu(); } } //命令有一个学生实现 public class Receiver { public void Run1000Meters() { Console.WriteLine("跑1000米"); } public void TiaoWu() { Console.WriteLine("跳舞……"); } }
如果需要扩展,在命令类、抽象类、实现类、学生类中进行声明即可,客户端不用修改,