策略模式跟工廠模式很像
我自己的理解,兩者的差別是這樣:
這次的範例是會員買商品,會有三種促銷情境
public interface Promotion {
String getType();
BigDecimal getPrice(BigDecimal originalPrice, BigDecimal discount, int quantity);
}
public class ItemPromotion implements Promotion {
@Override
public String getType() {
return "單件折扣";
}
@Override
public BigDecimal getPrice(BigDecimal originalPrice, BigDecimal discount, int quantity) {
BigDecimal price;
price = originalPrice.multiply(discount);
return price;
}
}
public class SecondItemPromotion implements Promotion {
@Override
public String getType() {
return "第二個商品折扣";
}
@Override
public BigDecimal getPrice(BigDecimal originalPrice, BigDecimal discount, int quantity) {
BigDecimal price;
price = originalPrice.multiply(discount);
price = price.add(originalPrice);
return price;
}
}
public class NoPromotion implements Promotion {
@Override
public String getType() {
return "沒有折扣";
}
@Override
public BigDecimal getPrice(BigDecimal originalPrice, BigDecimal discount, int quantity) {
BigDecimal price;
price = originalPrice.multiply(BigDecimal.valueOf(quantity));
return price;
}
}
getPayMoney
方法寫促銷策略public class Member {
private String name;
private Promotion promotion;
public Member(String name) {
this.name = name;
}
public BigDecimal getPayMoney(BigDecimal originalPrice, BigDecimal discount, int quantity) {
BigDecimal money;
switch (quantity) {
case 1:
promotion = new ItemPromotion();
money = promotion.getPrice(originalPrice, discount, quantity);
break;
case 2:
promotion = new SecondItemPromotion();
money = promotion.getPrice(originalPrice, discount, quantity);
break;
default:
promotion = new NoPromotion();
money = promotion.getPrice(originalPrice, discount, quantity);
break;
}
return money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Promotion getPromotion() {
return promotion;
}
public void setPromotion(Promotion promotion) {
this.promotion = promotion;
}
}
public class JavaTest {
@Test
public void show() {
StringBuilder text;
text = new StringBuilder();
text.append("\n");
text.append(getMemberText(new Member("Andy"), 1));
text.append("\n");
text.append(getMemberText(new Member("Jack"), 2));
text.append("\n");
text.append(getMemberText(new Member("Rich"), 100));
text.append("\n");
assertEquals("測試", text.toString());
}
private String getMemberText(Member member, int quantity) {
StringBuilder memberText;
memberText = new StringBuilder();
memberText.append("姓名:");
memberText.append(member.getName());
memberText.append(" / ");
memberText.append("折扣名稱:");
memberText.append(member.getPromotion().getType());
memberText.append(" / ");
memberText.append("付多少錢:");
memberText.append(member.getPayMoney(new BigDecimal("100"), new BigDecimal("0.8"), quantity));
return memberText.toString();
}
}
姓名:Andy / 折扣名稱:單件折扣 / 付多少錢:80.0
姓名:Jack / 折扣名稱:第二個商品折扣 / 付多少錢:180.0
姓名:Rich / 折扣名稱:沒有折扣 / 付多少錢:10000