設計模式面對面之命令模式
阿新 • • 發佈:2017-11-14
void 提交 ram 出現 mage receiver 分享 cut 設計
命令模式
類圖:
常用的實現方式:
指令處理對象
public interface IReceiver { void Operation(); }//end IReceiverView Code
public class ReceiverA : IReceiver { public ReceiverA(){ } public void Operation(){ Console.WriteLine("由ReceiverA處理"); } }//end ReceiverAView Code
public class ReceiverB : IReceiver { public ReceiverB(){ } public void Operation(){ Console.WriteLine("由ReceiverB處理"); } }//end ReceiverBView Code
指令對象
public interface ICommand { void Execute(); }//end ICommandView Code
public class CommandRealizeA : ICommand { private readonly IReceiver _receiver; public CommandRealizeA(){ _receiver=new ReceiverA(); } public void Execute(){ _receiver.Operation(); } }//end CommandRealizeAView Code
public classView CodeCommandRealizeB : 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 InvokerView Code
使用場景:
當每次請求或者動作會出現一連串操作,此時可以考慮。比如提交表單後臺涉及到數據庫操作,日誌操作,緩存操作等等,這些操作可以用命令模式去控制。
命令模式將命令的調用者(發出者),執行者,處理著,從一個緊耦合的動作,分離開來,主要用來復雜的動作解耦和指令(命令)管理。
設計模式面對面之命令模式