http://www.35java.com/zhibo/forum.php?mod=viewthread&tid=274&extra=page%3D2
| 在JavaSwing中的JTextArea元件预设并没有卷轴,因为设计人员认为卷轴的功能并不是一定需要的,而决定让程式人员可以动态选择是否增加卷轴功能,卷轴的功能是由JScrollPane元件提供,如果您要加入一个具有卷轴功能的JTextArea,您可以如下进行设计: JTextArea textArea = new JTextArea(); JScrollPane scrollPane = new JScrollPane(textArea); JScrollPane对JTextArea即是个容器,而它对JFrame来说又是个元件,可以如下这般将之加入JFrame中: getContentPane().add(scrollPane); 像这样动态的为JTextArea加入功能的方法,我们可以使用Decorator模式来组织结构,您可以动态的为一个物件加入一些功能(像是为JTextArea加上卷轴),而又不用修改JTextArea的功能。对JTextArea来说,JScrollPane就好像是一个卷轴外框,直接套在JTextArea上作装饰,就好比您在照片上加上一个相框的意思。 先以上面这个例子来说明Decorator模式的一个实例:
如上图所示的,无论是TextView或是Decorator类别,它们都是VisualComponent的一个子类,也就是说它们都是一个可视元件,而Decorator类又聚合了VisualComponent,所以又可以当作TextView容器,ScrollDecorator类别实作了Decorator类,它可能是这样设计的: public abstract class Decorator extends VisualComponent { protected VisualComponent component; public Decorator(VisualComponent component) { this.component = component; } public void draw() { component.draw(); } } public class ScrollDecorator extends Decorator { public ScrollDecorator(VisualComponent component) { super(component); } public void draw() { super.draw(); scrollTo(); } public void scrollTo() { // .... } } 要将新功能套用至TextView上,可以这样设计: ScrollDecorator scrollDecorator = new ScrollDecorator(new TextView()); super.draw()会先呼叫component也就是TextView物件的draw()方法先绘制TextView,然后再进行ScrollPanel的scrollTo(),也就是卷动的方法。在图中也表示了一个BorderDecorator,它可能是这样设计的: public class BorderDecorator extends Decorator { public BorderDecorator(VisualComponent component) { super(component); } public void draw() { super.draw(); drawBorder(); } public void drawBorder() { // .... } } 要将ScrollDecorator与BorderDecorator加至TextView上,我们可以这样设计: BorderDecorator borderDecorator = new BorderDecorator( new ScrollDecorator(new TextView())); 所以当BorderDecorator调用draw()方法时,它会先调用ScrollDecorator的draw()方法,而 ScrollDecorator的draw()方法又会先调用TextView的draw()方法,所以绘制的顺序变成: TextDraw.draw(); ScrollDecorator.scrollTo(); BorderDecorator.drawBorder(); 下图为物件之间的调用关系:
Decorator模式的 UML 结构图如下所示:
在Gof的书中指出另一个范例,它设计一个Stream抽象类,而有一个StreamDecorator类,Stream的子类有处理记忆体串流的MemoryStream与FileStream,有各种方法可以处理串流,也许只是单纯的处理字元,也许会进行压缩,也许会进行字元转换,最基本的处理可能是处理字元,而字元压缩被视为额外的功能,这个时候我们可以使用装饰模式,在需要的时候为Stream物件加上必要的功能,事实上在java.io中的许多输入输出物件,就是采取这样的设计。 |




浙公网安备 33010602011771号