分享

设计模式(1)装饰模式总结

 昵称10504424 2013-03-07

概述


动态为对象添加额外的功能,相对以前利用子类继承来增加父类的功能来说。装饰模式更为简洁、灵活,更符合面向


对象的原则。


装饰模式结构图

在Decorator类中,通过SetComponent构造函数来对Component对象进行设置,从而扩展Component的功能,

  1. namespace 装饰模式  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             ConcreteComponent c = new ConcreteComponent();  
  8.             ConcreteDecoratorA a = new ConcreteDecoratorA();  
  9.             ConcretedDecoratorB b = new ConcretedDecoratorB();  
  10.   
  11.             a.SetComponent(c);  
  12.             b.SetComponent(a);  
  13.             b.Operation();  
  14.   
  15.             Console.ReadLine();  
  16.         }  
  17.     }  
  18.     //Component类   
  19.     abstract class Component  
  20.     {  
  21.         public abstract  void Operation();  
  22.     }  
  23.     //ConcreteComponet类   
  24.     class ConcreteComponent : Component  
  25.     {  
  26.         public override void Operation()  
  27.         {  
  28.             Console.WriteLine("具体对象的操作!!!") ;  
  29.         }  
  30.     }  
  31.     //Decorator类   
  32.     abstract  class Decorator : Component  
  33.     {     
  34.         //设置Component   
  35.         protected Component component;  
  36.         public void SetComponent (Component component)  
  37.         {  
  38.             this.component = component;  
  39.         }  
  40.         public override void Operation()  
  41.         {  
  42.             if (component != null)  
  43.             {  
  44.                 component.Operation();  
  45.             }  
  46.         }  
  47.     }  
  48.     //ConcreteDecoratorA类   
  49.     class ConcreteDecoratorA :Decorator   
  50.     {  
  51.         private string addedState;  
  52.         public override void Operation()  
  53.         {  
  54.             base.Operation();  
  55.             addedState = "标识A的操作,以区别操作B!!!";  
  56.             Console.WriteLine ("具体对象A的操作!!!");  
  57.         }  
  58.     }  
  59.     //ConcreteDecoratorB类   
  60.     class ConcretedDecoratorB : Decorator  
  61.     {  
  62.         private string removeState;  
  63.         public override void Operation()  
  64.         {  
  65.             base.Operation();  
  66.             removeState = "标识操作B,以区别操作A!!!";  
  67.             Console.WriteLine("具体对象B的操作!!!");  
  68.         }  
  69.     }  
  70. }  


最后调用的实际上是Component的方法。


运行结果



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多