标签:
命令模式:将请求封装,用不同的请求对客户进行参数化,对请求排队或记录请求日志,及撤销操作。
1 namespace DesignModel.命令模式 2 { 3 abstract class Command 4 { 5 protected Execer exe; 6 public Command(Execer execer) 7 { 8 this.exe = execer; 9 } 10 abstract public void ExecCommand(); 11 } 12 13 class CommandOne : Command 14 { 15 public CommandOne(Execer execer) : base(execer) { } 16 public override void ExecCommand() 17 { 18 exe.ExecCommandOne(); 19 } 20 } 21 class CommandTwo : Command 22 { 23 public CommandTwo(Execer execer) : base(execer) { } 24 public override void ExecCommand() => exe.ExecCommandTwo(); 25 26 } 27 28 class Execer 29 { 30 public void ExecCommandOne() => Console.WriteLine(""); 31 public void ExecCommandTwo() => Console.WriteLine(""); 32 } 33 34 35 class Builder 36 { 37 IList<Command> list = new List<Command>(); 38 public Builder SetBuilder(Command command) 39 { 40 list.Add(command); 41 return this; 42 } 43 public void Remove(Command command) 44 { 45 list.Remove(command); 46 } 47 public void Notify() 48 { 49 list.All(x => { x.ExecCommand(); return true; }); 50 } 51 } 52 } 53 static void 命令模式() 54 { 55 Execer execer = new Execer(); 56 Command c1 = new CommandOne(execer); 57 Command c2 = new CommandTwo(execer); 58 var builder = new DesignModel.命令模式.Builder(); 59 builder.SetBuilder(c1).SetBuilder(c2).Notify(); 60 }
优点:
1可以设计命令队列;
2允许命令接收方否决命令;
3新增具体命令类不影响其它部分。
标签:
原文地址:http://www.cnblogs.com/liurui/p/5562598.html