Design Pattern - Structural - Decorator 模式
目的:
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
使用Decorator而不是继承的原因:
当需要扩展的功能的种类很多时,使用继承势必造成很多子类,增加系统的复杂性。
经典例子:
<<Head First Design Pattern>>里的咖啡吧例子。
基本咖啡有四种:HouseBlend,DarkRoast,Decaf,Espresso。
咖啡调味料四种:steamed milk, soy, mocha, whipped cream milk。
每种咖啡可以和一种或多种调味料混合形成新的咖啡。
此时如果使用继承,将会出现64个子类。而使用Decorator就会简单很多。
其他例子:
Java I/O标准为库的设计。
相关的模式:
Adapter
参考文章:
http://apps.hi.baidu.com/share/detail/20180365
http://www.233.com/JAVA/Instructs/060107/104056155.html
http://www.newsmth.net/pc/pcshowcom.php?cid=142543
http://www.it.com.cn/f/edu/053/21/89668.htm
浙公网安备 33010602011771号