适用场景,不断组合一些功能组件的时间用
JDK中,输入流输出流就用了这个模式 ()各种inputStrem传入返回inputStream)
UML图如下
Icar类
public interface ICar { void run(); }
car类
public class Car implements ICar{ @Override public void run() { System.out.println("普通的run"); } }
superCar类
public class SuperCar extends Car { private Car car; public SuperCar(Car car) { this.car = car; } public void run(){ car.run(); } }
这个是最核心的,因为重写的run方法,实际调用的是穿进来的car对象的run方法
AICar类
public class AiCar extends SuperCar { public AiCar(Car car) { super(car); } public void AiRun(){ System.out.println("ai run"); } @Override public void run() { AiRun(); super.run(); } }
Water类
public class WaterCar extends SuperCar { private Car car; public WaterCar(Car car) { super(car); } public void water(){ System.out.println("水上 run"); } @Override public void run() { water(); super.run(); } }
cient调用
public static void main(String[] args) { Car Car = new WaterCar( new AiCar(new Car())); Car.run(); }
效果如下: