命令模式(Command)

作者:追风剑情 发布于:2016-6-17 18:05 分类:设计模式

应用场景:将行为请求者与行为执行者解耦。


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace CommandTest
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. //实际开发中,还可以把各命令加入队列中,并支持撤销(Undo)操作和恢复(Redo)操作。
  12.  
  13. Receiver receiver = new Receiver();
  14. ICommand cmd1 = new Command1(receiver);
  15. ICommand cmd2 = new Command2(receiver);
  16.  
  17. cmd1.Execute();
  18. cmd2.Execute();
  19.  
  20. Console.Read();
  21. }
  22. }
  23.  
  24. public interface ICommand
  25. {
  26. void Execute();
  27. }
  28.  
  29. public class Command1 : ICommand
  30. {
  31. private Receiver receiver;
  32.  
  33. public Command1(Receiver receiver)
  34. {
  35. this.receiver = receiver;
  36. }
  37.  
  38. public void Execute()
  39. {
  40. receiver.Show1();
  41. }
  42. }
  43.  
  44. public class Command2 : ICommand
  45. {
  46. private Receiver receiver;
  47.  
  48. public Command2(Receiver receiver)
  49. {
  50. this.receiver = receiver;
  51. }
  52.  
  53. public void Execute()
  54. {
  55. receiver.Show2();
  56. }
  57. }
  58.  
  59. //命令接收者
  60. public class Receiver
  61. {
  62. public void Show1()
  63. {
  64.  
  65. }
  66.  
  67. public void Show2()
  68. {
  69.  
  70. }
  71. }
  72. }


标签: 设计模式

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号