转载自: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();
}
}