装饰模式:动态的给一个对象加一些额外的功能
public class App {
public static void main(String[] args) {
System.out.println("比比鸟出现了");
Troll troll=new SimpleTroll();
troll.attack();
System.out.println("比比鸟处于附魔状态,更加强大");
troll=new ClubbedTroll(troll);
troll.attack();
troll.fleeBattle();
}
}
public class ClubbedTroll implements Troll{
private Troll decorated;
public ClubbedTroll(Troll decorated){
this.decorated=decorated;
}
@Override
public void attack() {
decorated.attack();
System.out.println("附带伤害");
}
@Override
public int getAttackPower() {
return decorated.getAttackPower()+10;
}
@Override
public void fleeBattle() {
decorated.fleeBattle();
}
}
public class SimpleTroll implements Troll {
@Override
public void attack() {
System.out.println("比比鸟攻击了你");
}
@Override
public int getAttackPower() {
return 10;
}
@Override
public void fleeBattle() {
System.out.println("比比鸟逃跑了");
}
}
public interface Troll {
void attack();
int getAttackPower();
void fleeBattle();
}
解析:可以看出都是继承一个类,然后另一个