Decorator:Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
二:引入
假设现在有一家咖啡店,经营咖啡,茶等饮料,我们来为它设计一个系统。
问题:
饮料加糖或牛奶等调料时是要另收费的(每包1元),顾客可以要也可以不要,所以这个固定价格的cost方法不符合要求. 不符合OCP(open for extension,close for modification)
to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
for responsibilities that can be withdrawn.
when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.
参考文献: 1:阎宏,《Java与模式》,电子工业出版社 2:Eric Freeman & Elisabeth Freeman,《Head First Design Pattern》,O'REILLY