日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

《研磨设计模式》chap17 策略模式(1) 简介

發布時間:2025/3/21 asp.net 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《研磨设计模式》chap17 策略模式(1) 简介 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

客戶報價,價格有多種情況。

1. 正常思路解決:分成多個函數

public class Price {//報價,對不同類型的,計算不同的價格 public double quote(double goodsPrice,String customerType){if("普通客戶".equals(customerType)){return this.calcPriceForNormal(goodsPrice);}else if("老客戶".equals(customerType)){return this.calcPriceForOld(goodsPrice);}else if("大客戶".equals(customerType)){return this.calcPriceForLarge(goodsPrice); }//其余人員都是報原價return goodsPrice;}//為新客戶或者是普通客戶計算應報的價格 private double calcPriceForNormal(double goodsPrice){System.out.println("對于新客戶或者是普通客戶,沒有折扣");return goodsPrice;}//為老客戶計算應報的價格 private double calcPriceForOld(double goodsPrice){System.out.println("對于老客戶,統一折扣5%");return goodsPrice*(1-0.05);}

2. 策略模式簡介

public interface Strategy {//某個算法的接口,可以有傳入參數,也可以有返回值 public void algorithmInterface(); }public class ConcreteStrategyA implements Strategy { public void algorithmInterface() {//具體的算法實現 } }public class Context { private Strategy strategy; public Context(Strategy aStrategy) {this.strategy = aStrategy;} //上下文對客戶端提供的操作接口,可以有參數和返回值 public void contextInterface() {//通常會轉調具體的策略對象進行算法運算strategy.algorithmInterface();} }

3. 應用策略模式到場景

public interface Strategy { public double calcPrice(double goodsPrice); }public class CooperateCustomerStrategy implements Strategy{public double calcPrice(double goodsPrice) {System.out.println("對于戰略合作客戶,統一8折");return goodsPrice*0.8;} }public class Price {//持有一個具體的策略對象 private Strategy strategy = null; public Price(Strategy aStrategy){this.strategy = aStrategy;} public double quote(double goodsPrice){return this.strategy.calcPrice(goodsPrice);} }public static void main(String[] args) {//1:選擇并創建需要使用的策略對象Strategy strategy = new CooperateCustomerStrategy();//2:創建上下文Price ctx = new Price(strategy); //3:計算報價double quote = ctx.quote(1000);System.out.println("向客戶報價:"+quote);}

總結

以上是生活随笔為你收集整理的《研磨设计模式》chap17 策略模式(1) 简介的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。