I’m currently experimenting with decorators. I created a Tank class and two decorators: DoubleGunTank (shoots more powerfully) and FasterTank (drives faster). Here they are:
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;
}
}
What I’m trying to do is decorate one tank with both double gun and the super speed. So I do it like this:
Tank czolg = new Tank();
czolg = new FasterTank(czolg);
czolg = new DoubleGunTank(czolg);
System.out.println("Shoot: "+czolg.shoot());
System.out.println("Drive: "+czolg.drive());
But the result is:
Shoot: 200
Drive: 10
It seems that only one decorator activates both methods from the DoubleGunTank class. So my question is: how do I get the tank to shoot more powerfully and drive faster at the same time?
Not quite sure about the Decorator pattern but
czlog.drive()invokesTank.drive()becauseDoubleGunTankdoes not override it.You need to override every method in the superclass and delegate it to the contained
fTankfor this to work like you want it to.