顾名思义,装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。
//抽象的组件类,具体组件功能的抽象封装
public interface Component {
void doSomething();
}
//具体的组件类
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
// TODO Auto-generated method stub
System.out.println("开车");
}
}
//抽象的装饰类,继承抽象的组件类Component,并对其进行扩展
public abstract class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void doSomething() {
component.doSomething();
}
public abstract void time();
}
//具体的装饰类
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void addDoSomething() {
System.out.println("晚上");
}
@Override
public void time() {
System.out.println("Today ");
}
@Override
public void doSomething() {
this.time();
this.addDoSomething();
super.doSomething();
}
}
测试类:public class Test {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecorator(component);
decorator.doSomething();
}
}
装饰器模式的应用场景:
1、需要扩展一个类的功能,或给一个类增加附加责任
2、动态的为一个对象增加功能,而且还能动态撤销。
3、需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。