装饰模式-Decorator Pattern
自己的理解:具体构件和抽象装饰类继承抽象构件类,具体装饰类继承抽象装饰类,抽象构件类中有一个统一的方法,装饰的作用是为具体构件的这个方法加入额外的一些功能。(装饰类可以接收一个抽象构件类型,返回也是一个抽象构件类型)
● 抽象构件:它是具体构件和抽象装饰类的共同父类,声明了在具体构件中实现的业务方法,它的引入可以使客户端以一致的方式处理未被装饰的对象以及装饰之后的对象,实现客户端的透明操作。
● 具体构件:它是抽象构件类的子类,用于定义具体的构件对象,实现了在抽象构件中声明的方法,装饰器可以给它增加额外的职责(方法)。
● 抽象装饰类:它也是抽象构件类的子类,用于给具体构件增加职责,但是具体职责在其子类中实现。它维护一个指向抽象构件对象的引用,通过该引用可以调用装饰之前构件对象的方法,并通过其子类扩展该方法,以达到装饰的目的。
● 具体装饰类:它是抽象装饰类的子类,负责向构件添加新的职责。每一个具体装饰类都定义了一些新的行为,它可以调用在抽象装饰类中定义的方法,并可以增加新的方法用以扩充对象的行为。
抽象构件类
//抽象构件类
public abstract class Component {
public abstract void display();
}
抽象装饰类
//抽象装饰类
public class ComponentDecorator extends Component {
private Component component; //维持对抽象构件类型对象的引用
public ComponentDecorator(Component component) //注入抽象构件类型的对象
{
this.component = component;
}
public void display()
{
component.display();
}
}
具体构件
public class TextBox extends Component {
@Override
public void display() {
System.out.println("显示文本框");
}
}
public class ListBox extends Component {
@Override
public void display() {
System.out.println("显示列表框");
}
}
public class Window extends Component {
@Override
public void display() {
System.out.println("显示窗体");
}
}
具体装饰类
public class BlackBorderDecorator extends ComponentDecorator {
public BlackBorderDecorator(Component component) {
super(component);
}
public void display()
{
this.setBlackBorder();
super.display();
}
public void setBlackBorder()
{
System.out.println("为构件增加黑色边框!");
}
}
public class ScrollBarDecorator extends ComponentDecorator {
public ScrollBarDecorator(Component component) {
super(component);
}
public void display()
{
this.setScrollBar();
super.display();
}
public void setScrollBar()
{
System.out.println("为构件增加滚动条!");
}
}
Client
public class Client {
public static void main(String[] args) {
Component component,componentSB,componentDSB; //使用抽象构件定义
component = new Window(); //定义具体构件
componentSB = new ScrollBarDecorator(component); //定义装饰后的构件
componentDSB = new BlackBorderDecorator(componentSB);
componentDSB.display();
}
}