装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。
装饰模式包含如下角色:
Component: 抽象构件类
ConcreteComponent: 具体构件类
Decorator: 抽象装饰类
ConcreteDecorator: 具体装饰类
某软件公司基于面向对象技术开发了一套图形界面构件库VisualComponent,该构件库提供了大量基本构件,如窗体、文本框、列表框等,由于在使用该构件库时,用户经常要求定制一些特殊的显示效果如带滚动条的窗体、带黑色边框的文本框、既带滚动条又带黑色边框的列表框等等,因此经常需要对该构件库进行扩展以增强其功能。
uml图
package designpatterns.decorator;
//黑色边框装饰类,充当具体装饰类
public class BlackBorderDecorator extends ComponentDecorator{
public BlackBorderDecorator(Component component) {
super(component);
// TODO Auto-generated constructor stub
}
public void display() {
this.setBlackBorder();
super.display();
}
private void setBlackBorder() {
// TODO Auto-generated method stub
System.out.println("为构件增加黑色边框!");
}
}
//抽象界面构建类,充当抽象构建类
public abstract class Component {
public abstract void display();
}
public class ComponentDecorator extends Component{
private Component component; //维持对抽象构建类型对象的引用
//注入抽象构建类型的对象
public ComponentDecorator(Component component) {
this.component=component;
}
@Override
public void display() {
// TODO Auto-generated method stub
component.display();
}
}
//列表框类,充当具体构建类
public class ListBox extends Component{
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("显示列表框!");
}
}
//滚动条装饰类,充当具体装饰类
public class ScrolBarDecorator extends ComponentDecorator{
public ScrolBarDecorator(Component component) {
super(component);
}
public void display() {
this.setScrolBar();
super.display();
}
private void setScrolBar() {
// TODO Auto-generated method stub
System.out.println("为构件增加滚动条");
}
}
//文本框类,充当具体构建类
public class TextBox extends Component{
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("显示文本框");
}
}
//窗体类,充当具体构建类
public class Window extends Component{
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("显示窗体");
}
}
//客户端测试类
public class Client {
public static void main(String[] args) {
Component component,componentSB,componentBB; //使用抽象构件定义全部对象
component = new Window(); //创建具体构件对象
componentSB =new ScrolBarDecorator(component); //创建装饰后的构件对象
componentBB =new BlackBorderDecorator(componentSB); //将装饰了一次的对象注入另一个装饰类
componentBB.display();
}
}