类图:
常用的实现方式:
指令处理对象
public interface IReceiver { void Operation(); }//end IReceiver
public class ReceiverA : IReceiver { public ReceiverA(){ } public void Operation(){ Console.WriteLine("由ReceiverA处理"); } }//end ReceiverA
public class ReceiverB : IReceiver { public ReceiverB(){ } public void Operation(){ Console.WriteLine("由ReceiverB处理"); } }//end ReceiverB
指令对象
public interface ICommand { void Execute(); }//end ICommand
public class CommandRealizeA : ICommand { private readonly IReceiver _receiver; public CommandRealizeA(){ _receiver=new ReceiverA(); } public void Execute(){ _receiver.Operation(); } }//end CommandRealizeA
public class CommandRealizeB : ICommand { private readonly IReceiver _receiver; public CommandRealizeB() { _receiver=new ReceiverB(); } public void Execute(){ _receiver.Operation(); } }//end CommandRealizeB
调用对象
public class Invoker { private ICommand _command; public Invoker(){ _command=new CommandRealizeA();//默认指令 } public void Invoke() { _command.Execute(); } /// /// <param name="command"></param> public void SetCommand(ICommand command) { _command = command; } }//end Invoker
使用场景:
当每次请求或者动作会出现一连串操作,此时可以考虑。比如提交表单后台涉及到数据库操作,日志操作,缓存操作等等,这些操作可以用命令模式去控制。
命令模式将命令的调用者(发出者),执行者,处理着,从一个紧耦合的动作,分离开来,主要用来复杂的动作解耦和指令(命令)管理。
原文:http://www.cnblogs.com/dujq/p/7832927.html