題目:某軟體公司基于面向對象技術開發了一套圖形界面顯示構件庫VisualComponent。在使用該庫建構某圖形界面時,使用者要求為界面定制一些特效顯示效果,如帶滾動條的窗體或透明窗體等。現使用裝飾模式設計該構件庫,繪制類圖并程式設計模拟實作。
類圖
Client
package 裝飾模式;
//抽象界面構件類:抽象構件類,為了突出與模式相關的核心代碼,對原有控件代碼進行了大量的簡化
abstract class Component
{
public abstract void display();
}
//窗體類:具體構件類
class Window extends Component
{
public void display()
{
System.out.println("顯示窗體!");
}
}
//文本框類:具體構件類
class TextBox extends Component
{
public void display()
{
System.out.println("顯示文本框!");
}
}
//清單框類:具體構件類
class ListBox extends Component
{
public void display()
{
System.out.println("顯示清單框!");
}
}
//構件裝飾類:抽象裝飾類
class ComponentDecorator extends Component
{
private Component component; //維持對抽象構件類型對象的引用
public ComponentDecorator(Component component) //注入抽象構件類型的對象
{
this.component = component;
}
public void display()
{
component.display();
}
}
//滾動條裝飾類:具體裝飾類
class ScrollBarDecorator extends ComponentDecorator
{
public ScrollBarDecorator(Component component)
{
super(component);
}
public void display()
{
this.setScrollBar();
super.display();
}
public void setScrollBar()
{
System.out.println("為構件增加滾動條!");
}
}
//黑色邊框裝飾類:具體裝飾類
class BlackBorderDecorator extends ComponentDecorator
{
public BlackBorderDecorator(Component component)
{
super(component);
}
public void display()
{
this.setBlackBorder();
super.display();
}
public void setBlackBorder()
{
System.out.println("為構件增加黑色邊框!");
}
}
class Client
{
public static void main(String args[])
{
Component component,componentSB,componentBB; //全部使用抽象構件定義
component = new Window();
componentSB = new ScrollBarDecorator(component);
componentSB.display();
System.out.println("----------------");
componentBB = new BlackBorderDecorator(componentSB); //将裝飾了一次之後的對象繼續注入到另一個裝飾類中,進行第二次裝飾
componentBB.display();
}
}
運作效果圖