裝飾模式讀完後,最好的理解就是稱號的概念
例如我們有個會員系統
夥伴
很油
稱號,變成很油夥伴
狂熱
稱號,變成狂熱很油夥伴
public interface Fans {
String getTitle();
}
public abstract class Title implements Fans {
protected Fans fans;
public Title(Fans fans) {
this.fans = fans;
}
@Override
public String getTitle() {
return fans.getTitle();
}
}
夥伴
public class Member implements Fans {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getTitle() {
return "夥伴";
}
}
很油
類別,用來當稱號public class Oil extends Title {
public Oil(Fans fans) {
super(fans);
}
@Override
public String getTitle() {
return "很油" + super.getTitle();
}
}
狂熱
類別,用來當稱號public class Fire extends Title {
public Fire(Fans fans) {
super(fans);
}
@Override
public String getTitle() {
return "狂熱" + super.getTitle();
}
}
StringBuilder text = new StringBuilder();
Fans member = new Member();
text.append("\n");
text.append("會員加入獲得稱號: ");
text.append(member.getTitle());
text.append("\n");
Oil oil = new Oil(member);
text.append("會員花一千獲得稱號: ");
text.append(oil.getTitle());
text.append("\n");
Fire fire = new Fire(oil);
text.append("會員花一萬獲得稱號: ");
text.append(fire.getTitle());
text.append("\n");
assertEquals("測試", text.toString());
會員加入獲得稱號: 夥伴
會員花一千獲得稱號: 很油夥伴
會員花一萬獲得稱號: 狂熱很油夥伴