标签:
将“行为请求者”与“行为实现者”解耦,将一组行为(命令)抽象为对象,实现二者之间的松耦合。
其实其实现与经典的命令模式的类图是相似的,如下
1 /// <summary> 2 /// 命令执行者 3 /// </summary> 4 public class Invoker 5 { 6 private IList<ICommand> commands = new List<ICommand>(); 7 public void AddCommand(ICommand command) 8 { 9 commands.Add(command); 10 } 11 12 public void RemoveCommand(ICommand command) 13 { 14 commands.Remove(command); 15 } 16 public void Invoke() 17 { 18 foreach (ICommand cmd in commands) 19 { 20 cmd.Excute(); 21 } 22 } 23 } 24 /// <summary> 25 /// 命令接口 26 /// </summary> 27 public interface ICommand 28 { 29 void Excute(); 30 } 31 /// <summary> 32 /// 命令实现类 33 /// </summary> 34 public class ConcreteCommand : ICommand 35 { 36 IReceiver receiver = null; 37 public ConcreteCommand(IReceiver receiver) 38 { 39 this.receiver = receiver; 40 } 41 public void Excute() 42 { 43 receiver.Action(); 44 } 45 } 46 /// <summary> 47 /// 实际接收者接口 48 /// </summary> 49 public interface IReceiver 50 { 51 void Action(); 52 } 53 /// <summary> 54 /// Tv 55 /// </summary> 56 public class TvReceiver:IReceiver 57 { 58 public void Action() 59 { 60 Console.WriteLine("Tv show"); 61 } 62 } 63 /// <summary> 64 /// light 65 /// </summary> 66 public class LightReceiver : IReceiver 67 { 68 public void Action() 69 { 70 Console.WriteLine("Ligth up"); 71 } 72 } 73 74 /// <summary> 75 /// client 76 /// </summary> 77 public class Client 78 { 79 public void Test() 80 { 81 IReceiver receiver = new LightReceiver(); 82 ConcreteCommand cmd = new ConcreteCommand(receiver); 83 Invoker invoker = new Invoker(); 84 invoker.AddCommand(cmd); 85 cmd.Excute(); 86 } 87 }
命令模式是将行为抽象成对象。当然上面的代码并未能真正说明其本意,只是一个实现形式的展现。实际应用中,对行为进行“记录、撤销/重做、事务”等处理,如果将行为请求和实现用的直接调用的紧耦合实现的话,代码与逻辑就会相对的复杂,并且不易维护。但当我们用命令模式进行解耦时会发现其实现起来就方便多了。
标签:
原文地址:http://www.cnblogs.com/Joy-et/p/4856592.html