用通俗的话理解设计模式--Decorator pattern

来源:互联网 发布:阿振网络随笔 编辑:程序博客网 时间:2024/06/05 09:08

it's much messy to understand Decorator pattern.

 

The first intend of this pattern is providing powerful functions rather by inheriting but by composition. I think this key point is under my understable line.  The second intend of this pattern is to utlize the power of extension in runtime rather than in compile time.

 

The second intend  is acutally to use the power of the abstract class and to create an instance of a derived class that inherits an abstract class.

 

so what make my mind messy is that the abstract class, and the compile time versus the runtime.

My question1:

       if there are two classes derived from the same abstract class, for example,

      

public abstract class Beverage{  public abstract string GetDescription();  }public abstract class class1:Beverage{  public override string GetDescription()  {    return "class1";  }}public abstract class class2 : Beverage{  public override string GetDescription()  {    return "class2";  }}

 

 

what does it means when I code like this following

Beverage test=new class1();test=new class2();



 

My question2:

       when I inherit behavior by subclassing, that behavior is set statically at compile time. In addition, all subclasses must inherit the same behavior. If however, I can extend an object's behavior through composition, then I can do this danamically at runtime.

Whatever, the decorator pattern could add responsibilities to object dynamically which seems very attractive and glory. What'more, to multiply an object's responsiblities is worked by a step-down instance creation.

 

A gold rule "Open to extension and closed to modifcaiton " is also featured by the decorator pattern