设计模式(四)装饰器模式
装饰器模式
1、意图
动态增加功能,相比于继承更加灵活
2、类图
Component(VisualComponent):定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent(TextView):定义一个对象,可以给这个对象添加一些职责。
Decorator:维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。ConcreteDecorator(BorderDecorator、ScrollDecorator):向组件添加职责。
3、实现
public interface Component {
void draw();
}
public class ConcreteComponent implements Component{
@Override
public void draw() {
System.out.println("展示一个窗口");
}
}
抽象类实现接口
public abstract class Decorator implements Component{
public Component component;
Decorator(Component component){
this.component=component;
}
@Override
public void draw() {
component.draw();
}
}
public class ConcreteDecorator1 extends Decorator{
ConcreteDecorator1(Component component) {
super(component);
}
@Override
public void draw() {
System.out.println("给窗口加边框");
super.draw();
}
}
public class ConcreteDecorator2 extends Decorator{
ConcreteDecorator2(Component component) {
super(component);
}
@Override
public void draw() {
System.out.println("给窗口加滚动条");
super.draw();
}
}
public class test {
public static void main(String[] args) {
Component concreteComponent=new ConcreteComponent();
Decorator decorator1=new ConcreteDecorator1(concreteComponent);
decorator1.draw();
System.out.println("------------------------------");
Decorator decorator2=new ConcreteDecorator2(concreteComponent);
decorator2.draw();
}
}
4、效果