Java设计模式之装饰者模式
装饰者设计模式的前提条件:
- 增强类和被增强类必须实现同一个接口
- 增强类中要有引用指向被增强类
增强类和被增强类共同实现的接口(以Car举例):
package demo2;
public interface Car {
public abstract void run();
public abstract void stop();
}
需要被增强的类(奇瑞QQ):
package demo2;
public class QQ implements Car {
@Override
public void run() {
System.out.println("QQ能跑60迈!");
}
@Override
public void stop() {
System.out.println("QQ刹车....停住");
}
}
增强类CarWapper:
package demo2;
public class CarWrapper implements Car {
private Car car;
public CarWrapper(Car car) {
this.car = car;
}
@Override
public void run() {
System.out.println( "增强后,超过100迈。");
}
@Override
public void stop() {
car.stop();
}
}
测试类WapperTest:
package demo2;
public class WapperTest {
/**
* 装饰者模式前提条件:
* 1.被增强类和增强类必须实现同一个接口
* 2.增强类要有引用指向被增强类
* @param args
*/
public static void main(String[] args) {
Car car = new CarWrapper(new QQ());
car.run();
car.stop();
}
}
被增强后: