轉載自:http://blog.csdn.net/xu__cg/article/details/53024490 抽象構件 具體構建 裝飾角色 具體裝飾角色 客戶端 ...
轉載自:http://blog.csdn.net/xu__cg/article/details/53024490
抽象構件
public interface CarInterface { void move(); }
具體構建
public class Car implements CarInterface { public void move() { System.out.println("路上行駛"); } }
裝飾角色
public class SuperCar implements CarInterface { protected CarInterface car; public SuperCar(CarInterface car) { this.car = car; } public void move() { car.move(); } }
具體裝飾角色
/** * 飛行汽車 */ public class FlyCar extends SuperCar { public FlyCar(CarInterface car) { super(car); } public void fly() { System.out.println("空中行駛汽車"); } @Override public void move() { super.move(); fly(); } } /** * 水上汽車 */ public class WaterCar extends SuperCar { public WaterCar(CarInterface car) { super(car); } public void swim() { System.out.println("水上行駛汽車"); } @Override public void move() { super.move(); swim(); } }
客戶端
public class Client { public static void main(String[] args) { System.out.println("------普通汽車,正常行駛-----"); Car car = new Car(); car.move(); System.out.println("------增加新功能,飛行------"); FlyCar flyCar = new FlyCar(car); flyCar.move(); System.out.println("------新增加功能,水上行駛-----"); WaterCar waterCar = new WaterCar(car); waterCar.move(); System.out.println("-----新增加兩個功能,飛行與水上行駛-----"); WaterCar waterCar2 = new WaterCar(flyCar); waterCar2.move(); } }