ITeye博客

Design Pattern -- Decorator

dr2tr · 2007-03-09 14:36 · Markdown

Decorator 模式, 其功能为;Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.  

类图表示为:

解释一下这张图,这个模式主要有两点:

1。所需功能(Operation) 的部分实现是通过继承一个接口(或父类,通常也是Decoratee的父类)得到的

2。Decorator 通常聚合有它与Dectratee的(公共)父类

比较简单的关于这个的例子是改造Swing中JScrollPane和JTextArea的一种设计。我们知道,JTextArea需要卷轴的话,需要把它放到JScrollPane上。比如:

JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);

对此,我们可以通过Decrator模式进行改造试验。

如类图:

Decorator

以TextView 作为JTextArea,之前所说的功能我们只需要:

ScrollDecorator scrollDecorator = 
                    new ScrollDecorator(new TextView());

就可以完成了。

有关这个模式,经常有说起Java IO 中String 的设计。这里不做多说,因为网上相关资料应该不少。另外,Decorator 和Composite,Decorator 和State、Strategy 的区别,有空再写吧。

参考:

http://en.wikipedia.org/wiki/Decorator_pattern

http://www.nshen.net/designpattern/DesignPattern/DecoratorPattern.htm

http://www.dofactory.com/Patterns/PatternDecorator.aspx

http://www.cnblogs.com/singlepine/archive/2005/10/30/265023.html

http://www.enet.org.cn/Article/wybc/qtlb/200603/Article_14822.html

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。