装饰器模式,就是在被装饰对象上添加一层装饰,使用户直接操作装饰类就可对被装饰对象进行操作。
问:使用装饰器模式和直接使用继承有什么区别
答:直接使用继承在被装饰对象较多时会导致子类骤增,装饰器模式可以理解为和桥接模式一样是为了解决子类过多问题的解决方案,二者差别在于桥接模式是单纯为了解决多个独立维度变化,而装饰器模式是为了在源操作上加新的操作。
JDK中io即是使用装饰器模式:
OutputStream out = new DataOutputStream( new FileOutputStream( "test.txt") )
UML图:
定义一个需要被装饰接口,所有具体被装饰类都需要实现该接口:
interface Component{
void operation();
}
具体实现类(可以有多种):
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("one function in ConcreteComponent");
}
}
装饰器父类所有具体装饰器类都继承该类,实现了Component接口,重写被装饰类的方法:
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
继承装饰器类的具体装饰类,具体实现了原有基础上新增的方法:
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void anotherOperation() {
System.out.println("another operation");
}
@Override
public void operation() {
super.operation();
anotherOperation();
}
}
客户端中的使用方法类似桥接模式:
ConcreteDecorator cd = new ConcreteDecorator(new ConcreteComponent());
cd.operation();
ConcreteDecorator cd1 = new ConcreteDecorator(new ConcreteComponent1());
cd1.operation();
JAVA代码:https://github.com/zhuaizhuaixi/design-pattern/tree/master/src/designpattern/structural/decorator