0
我在學習裝飾器模式。這是一個非常簡單的角色設計,應該能夠裝備不同的物體。問題出現在字符的所有屬性設置爲0.贊助人裝飾器的私有屬性設置爲0.0
public abstract class Character{
private double damage;
public Character();
public void setDamage(damage){
this.damage = damage;
}
public double getDamage(){return damage;}
}
public class Human extends Character{
public Human(){
damage = 10.00;
}
}
public abstract class Object extends Character{
public abstract String getDescription();
}
public class Sword extends Object{
Character character;
public Sword(Character character){
this.character = character;
updateDamage();
}
public String getDescription(){
// Something
}
public void updateDamage(){
character.setDamage(character.getDamage() + 2.00);
}
}
下面是一個簡單的輸出。
public class Main{
public static void main(String[] args){
Character test = new Human();
System.out.printl(test.getDamage());
test = new Sword(test);
System.out.printl(test.getDamage());
}
// OUTPUT
10.0
0.0
這是怎麼發生的?有沒有比裝飾模式更好的實現呢?