命令模式(Command)
命令模式(Command),将一个请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化;对请求排队或者记录日志,以及支持可撤销的操作。
命令模式结构图
无,以后将会重构。
命令模式代码结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| Receiver r = new Receiver(); Command c = new ConcreteCommand(r); Invoker i = new Invoker(); i.SetCommand(c); i.ExecuteCommand();
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() { throw new NotImplementedException(); } }
class Invoker { private Command command;
public void SetCommand(Command command) { this.command = command; } public void ExecuteCommand() { command.Execute(); } }
class Receiver { public void Action() { } }
|
命令模式总结
命令模式优点:
它能够较容易地设计一个命令队列;
在需要的情况下,可以较容易地将命令计入日志;
允许接收请求的一方决定是否要否决请求;
容易地实现对请求的撤销和重做;
由于加进新的具体命令类不影响其他的类,因此增加新的具体命令非常容易。
命令模式把请求一个操作的对象和知道如何执行操作的对象分离开。