装饰者模式(Decorator)
通过一种对客户端透明的方式来扩展对象的功能,是extend的替代方案。比如开发一种车,能飞,能跑,还能游。
避免过多的子类生成(能飞能游的车。 能跑能飞的车。等等)
public interface Car { void show(); } public class BMWCar implements Car { @Override public void show() { System.out.println("i am bao ma car"); } } public abstract class CarDecorator implements Car { public Car car; public CarDecorator(Car car){ this.car = car; } } */ public class SwimCarDecorator extends CarDecorator { public SwimCarDecorator(Car car) { super(car); } @Override public void show() { this.car.show(); this.swim(); } public void swim(){ System.out.println("i can swim"); } } public class FlyCarDecorator extends CarDecorator { public FlyCarDecorator(Car car) { super(car); } @Override public void show() { this.car.show(); this.fly(); } public void fly(){ System.out.println("i can fly"); } }
Car bmw = new BMWCar(); bmw.show(); LOGGER.info("****************"); Car flyCar = new FlyCarDecorator(bmw); flyCar.show(); LOGGER.info("****************"); Car swimCar = new SwimCarDecorator(bmw); swimCar.show(); LOGGER.info("****************"); Car swimFlyCar = new SwimCarDecorator(flyCar); swimFlyCar.show();