package wrapper;
//创建一个接口
public interface ICar {
void move();
}
//一个实体类实现这个接口
class Car implements ICar{
@Override
public void move() {
// TODO Auto-generated method stub
System.out.println("陆地上跑!");
}
}
//装饰器角色也实现了这个接口 并有指向实体类的属性。
class SuperCar implements ICar{
protected ICar car;
public SuperCar(ICar car) {
super();
this.car = car;
}
@Override
public void move() {
// TODO Auto-generated method stub
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(){
super.move();
swim();
}
}
//具体装饰器继承装饰器
class AICar extends SuperCar{
public AICar(ICar car) {
super(car);
// TODO Auto-generated constructor stub
}
public void auto(){
System.out.println("自动跑");
}
@Override
public void move(){
super.move();
auto();
}
}
//测试一下
package wrapper;
public class Client {
public static void main(String[] args) {
Car car=new Car();
// car.move();
System.out.println("增加新的功能");
FlyCar fly=new FlyCar(car);
WaterCar wC=new WaterCar(new FlyCar(car));
wC.move();
}
}