1 动态地给一个对象添加一些额外的职位,就增加功能来说,装饰模式比生成子类更加灵活。
创建接口,定义要装饰的操作:
整体结构:
public interface Component {
public void operation();
}
被装饰的操作:
public class ConcreteComponent implements Component {
@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("具体对象的操作");
}
}
装饰抽象类:
public abstract class Decorator implements Component {
private Component component;
@Override
public void operation() {
// TODO Auto-generated method stub
if(component !=null){
component.operation();
}
}
public void setComponent(Component component) {
this.component = component;
}
}
具体装饰对象A的操作:
public class ConcreteDecoratorA extends Decorator {
@Override
public void operation() {
// TODO Auto-generated method stub
super.operation();
System.out.println("具体装饰对象A的操作");
}
}
具体装饰对象B的操作:
public class ConcreteDecoratorB extends Decorator {
@Override
public void operation() {
// TODO Auto-generated method stub
super.operation();
System.out.println("具体装饰对象B的操作");
}
}
测试:
public class TextMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcreteComponent concreteComponent=new ConcreteComponent();
ConcreteDecoratorA concreteDecoratorA=new ConcreteDecoratorA();
ConcreteDecoratorB concreteDecoratorB=new ConcreteDecoratorB();
concreteDecoratorA.setComponent(concreteComponent);
concreteDecoratorB.setComponent(concreteDecoratorA);
concreteDecoratorB.operation();
}
}
装饰者模式通过引入第抽象类和具体操作类来完成对具体对象的操作。摒弃之前通过添加子类的方式来扩展的效果。