我目前正在尝试使用装饰器。我创建了一个 Tank 类和两个装饰器:DoubleGunTank(射击更强大)和 FasterTank(开得更快)。他们来了:
public class Tank {
public int shoot() {
return 100;
}
public int drive() {
return 10;
}
}
public class FasterTank extends Tank {
protected Tank fTank;
public FasterTank(Tank tank) {
fTank = tank;
}
public int drive() {
return fTank.drive() * 2;
}
}
public class DoubleGunTank extends Tank {
protected Tank fTank;
public DoubleGunTank(Tank tank) {
fTank = tank;
}
public int shoot() {
return fTank.shoot() * 2;
}
}
我想做的是用双枪和超高速装饰一辆坦克。所以我这样做:
Tank czolg = new Tank();
czolg = new FasterTank(czolg);
czolg = new DoubleGunTank(czolg);
System.out.println("Shoot: "+czolg.shoot());
System.out.println("Drive: "+czolg.drive());
但结果是:
Shoot: 200
Drive: 10
似乎只有一个装饰器激活了 DoubleGunTank 类的两种方法。所以我的问题是:我怎样才能让坦克的射击更有力,同时开得更快?