策略模式:將可變的部分從程序中抽象分離成算法接口,在該接口下分別封裝一系列算法實現。並使他們能夠相互替換,從而致使客戶端程序獨立於算法的改變。java
優勢:算法
缺點:ide
//策略接口 public interface MemberStrategy { /** * 計算圖書的價格 * @param bookPrice 圖書的原價 * @return 打折後的價格 */ public double calcPrice(double bookPrice); } //初級會員優惠策略 public class PrimaryMemberStrategy implements MemberStrategy{ @Override public double calcPrice(double bookPrice) { System.out.println("初級會員沒有折扣"); return bookPrice; } } //中級會員優惠策略 public class IntermediateMemberStrategy implements MemberStrategy{ @Override public double calcPrice(double bookPrice) { System.out.println("中級會員折扣20%"); return bookPrice * 0.8; } } //高級會員優惠策略 public class AdvancedMemberStrategy implements MemberStrategy { @Override public double calcPrice(double bookPrice) { System.out.println("高級會員折扣50%"); return bookPrice * 0.5; } } // public class Price { private MemberStrategy memberStrategy; public Price(MemberStrategy memberStrategy){ this.memberStrategy = memberStrategy; } public double quote(double bookPrice){ return this.memberStrategy.calcPrice(bookPrice); } } //測試 public static void main(String[] args) { MemberStrategy strategy = new AdvancedMemberStrategy(); Price price = new Price(strategy); System.out.println(price.quote(200D)); }