将一个命令封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作
优点:
1.比较容易设计出一个命令队列
2.在需要的情况下,可以比较容易地将命令记入日志
3.允许接收请求的一放决定是否要否决请求
4.容易实现对于请求的撤销与重做
5.由于加入新的具体命令类不影响其他的类,因此增加新的具体命令类很容易
6.把请求一个操作的对象与知道怎么执行一个操作的对象分割开
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 设计模式 { abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } abstract public void Execute(); } class ConcreteCommand:Command { public ConcreteCommand(Receiver receiver) : base(receiver) {} public override void Execute() { receiver.Action(); } } class Invoker { private Command command; public void SetCommand(Command command) { this.command = command; } public void ExcuateCommand() { command.Execute(); } } class Receiver { public void Action() { Console.WriteLine("执行请求"); } } class Program { static void Main(string[] args) { Invoker i = new Invoker(); Receiver r = new Receiver(); ConcreteCommand c = new ConcreteCommand(r); i.SetCommand(c); i.ExcuateCommand(); Console.Read(); } } }