简单的装饰者模式列子
什么是装饰者模式
装饰者模式,是 23种常用的面向对象软件的设计模式之一.
动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更加有弹性的替代方案。
装饰者的作用:改写已存在的类的某个方法或某些方法, 增强方法的逻辑
使用装饰者模式需要满足的条件
1.增强类和被增强类实现的是同一个接口
2.增强类里面要拿到被增强类的引用
/** * 造车的规范 */ public interface Car { void run(); }
/** * 被增强的类 */ public class Byd implements Car { @Override public void run() { System.out.println("速度70迈"); } }
/** * 增强的类 */ public class WrapperCar implements Car { private Byd byd; public WrapperCar(Byd byd) { this.byd = byd; } @Override public void run() { System.out.println("速度200迈"); } }
测试方法:
public class Test { public static void main(String[] args) { Byd byd = new Byd(); WrapperCar wrapperCar = new WrapperCar(byd); wrapperCar.run(); //速度200迈 } }