每天一个设计模式之Decorator

http://www.oodesign.com/decorator-pattern.html

 

前面一天是composite,所以今天就看decorator了。

 

下面这句话总结的很好:

想要扩展一个对象的功能,可以通过继承的方式静态(编译时)实现。然而有时必须在运行时动态的扩展一个对象的功能。

 

再提咖啡店的例子:咖啡店出售咖啡,或加了各种糖或调料的咖啡。我们需要在运行的时候,决定这是一个什么样的对象:pure coffee 或者是加了其他东西的咖啡。对于后者,就是一个在运行时加入了其他对象(糖)的对象。

  • The intent of this pattern is to add additional responsibilities dynamically to an object

 

  • Component - Interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent - Defines an object to which additional responsibilities can be added. 就相当于咖啡
  • Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface. 相当于加了糖的咖啡,是一个复合对象。
  • Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior. 可以用于添加的各种对象,相当于糖,牛奶等。

Consequences

  • Decoration is more convenient for adding functionalities to objects instead of entire classes at runtime. With decoration it is also possible to remove the added functionalities dynamically.
  • Decoration adds functionality to objects at runtime which would make debugging system functionality harder.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值