定义:
动态的给一个对象添加额外的职责,就增加功能来说,装饰模式相比生成子类更为灵活。
其通用类图如下:
装饰模式的优点:
1、装饰类和被装饰类可以独立发展,互不耦合,因为装饰类是从外部来扩展被装饰类的功能的,所以Component无需知道Decorator
2、装饰模式是继承关系的一个替代方案,当继承的时候,如果需要生成很多的子类,才能解决问题,那么就会降低系统的灵活性,维护也不容易,所以可以使用装饰模式来解决类的膨胀问题。而且继承是静态的给类增加功能,而装饰模式是动态的添加功能,还可以动态的取消。
3、扩展性非常好。
需要注意的事项:
尽量避免多层的装饰,会增加系统的复杂度。
上面的源代码如下:
/*
* 最原始的抽象构件
*/
public abstract class Component {
public abstract void opration();
}
public class ConcreteComponent extends Component {
@Override
public void opration() {
System.out.println("this is the core role...");
}
}
/*
* 抽象装饰者类,继承自Component,并将其中的opration()方法委托给component
*/
public abstract class Decorator extends Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void opration() {
this.component.opration();
}
}
/*
* 具体的装饰类
*/
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
//自己定义的装饰方法
private void method(){
System.out.println("decorator A");
}
//重写父类的opration()方法
@Override
public void opration() {
method();
super.opration();
}
}
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
//自己定义的装饰方法
private void method(){
System.out.println("decorator B");
}
//重写父类的opration()方法
@Override
public void opration() {
super.opration();
method();
}
}
public class Client {
public static void main(String[] args) {
Component component=new ConcreteComponent();
Decorator decoratorA=new ConcreteDecoratorA(component);
decoratorA.opration();
System.out.println("-----------------");
Decorator decoratorB=new ConcreteDecoratorB(component);
decoratorB.opration();
}
}