代码实现
public interface ICar { void move(); }
抽象构建角色
//具体构件角色(真实对象,被装饰角色) class Car implements ICar{ @Override public void move() { System.out.println("陆地上跑"); } }
具体构建角色
//装饰角色 class SuperCar implements ICar{ private ICar car; public SuperCar(ICar car) { super(); this.car = car; } @Override public void move() { car.move(); } }
装饰角色
//具体装饰角色 class FlyCar extends SuperCar{ public FlyCar(ICar car) { super(car); // TODO Auto-generated constructor stub } public void fly(){ System.out.println("天上飞"); } @Override public void move() { // TODO Auto-generated method stub super.move(); fly(); } } class WaterCar extends SuperCar{ public WaterCar(ICar car) { super(car); // TODO Auto-generated constructor stub } public void swim(){ System.out.println("水中游"); } @Override public void move() { // TODO Auto-generated method stub super.move(); swim(); } } class AICar extends SuperCar{ public AICar(ICar car) { super(car); // TODO Auto-generated constructor stub } public void autoMove(){ System.out.println("自动驾驶"); } @Override public void move() { // TODO Auto-generated method stub super.move(); autoMove(); } }
具体装饰角色
public class Client { public static void main(String[] args) { Car car = new Car(); car.move(); // System.out.println("增加新的功能,飞行-------"); // FlyCar flycar = new FlyCar(car); // flycar.move(); // // System.out.println("增加新的功能,水中游-------"); // WaterCar waterCar = new WaterCar(flycar); // waterCar.move(); System.out.println("增加两个新功能,飞行,水里游---"); WaterCar waterCar2 = new WaterCar(new FlyCar(car)); waterCar2.move(); } }
调用测试
时间: 2024-11-06 09:44:14