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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值