讀完狀態模式後,發覺跟裝飾模式有一點類似
如果用稱號來說,裝飾模式可以加很多上去
但是狀態模式只有一個狀態,依照特定的值來改變
public interface Level {
String status(Member member);
}
public class Member {
private String name;
private BigDecimal money;
private Level level;
public Member() {
money = BigDecimal.ZERO;
level = new Copper();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public void addMoney(BigDecimal money) {
this.money = this.money.add(money);
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public String checkout() {
StringBuilder text;
text = new StringBuilder();
text.append("結帳完成");
text.append(" / ");
text.append("會員名稱:");
text.append(name);
text.append(" / ");
text.append("累計銷費金額:");
text.append(this.money.toPlainString());
text.append(" / ");
text.append("會員狀態:");
text.append(this.level.status(this));
return text.toString();
}
}
public class Copper implements Level {
@Override
public String status(Member member) {
StringBuilder text;
text = new StringBuilder();
if (member.getMoney().compareTo(BigDecimal.valueOf(500)) < 0) {
text.append("消費五百以下,還是銅會員");
} else {
member.setLevel(new Silver());
member.checkout();
text.append("消費超過五百,成為銀會員");
}
return text.toString();
}
}
public class Silver implements Level {
@Override
public String status(Member member) {
StringBuilder text;
text = new StringBuilder();
if (member.getMoney().compareTo(BigDecimal.valueOf(1000)) < 0) {
text.append("消費一千以下,還是銀會員");
} else {
member.setLevel(new Gold());
member.checkout();
text.append("消費超過一千,成為金會員");
}
return text.toString();
}
}
public class Gold implements Level {
@Override
public String status(Member member) {
StringBuilder text;
text = new StringBuilder();
text.append("升級到金會員,無法再升級");
return text.toString();
}
}