一:使用场景
假如领导要让我们做个报价方案。
那我们可定会有这样的情况,
1.新用户或者普通用户,报市场价
2.老用户给9.5折
3.优质客户或大客户给9折
二:不用设计模式,普通我们的 开发代码
/**
* 报价管理不同等级的用户,价格不一样
* @author dy
* @since 2016-08-10 & JDK 1.8.0_91
*/
public class Price_ {
/**
* 这里不用设计模式的解决方案
*/
public double quote(double goodPrice,String customerType){
switch (customerType){
case "普通客户":
return goodPrice;
case "老客户":
return goodPrice*0.95;
case "大客户":
return goodPrice*0.90;
default:
return goodPrice;
}
}
}
作为一个老鸟程序员,不用多说这样写可定code review 过不去,可能会被吐槽...
三,解决方案,这里我们引入策略模式,
下面是策略模式的结构和说明:
四:我们用策略模式实现报价管理
/**
* 报价管理不同等级的用户,价格不一样
*
* @author dy
* @since 2016-08-10 & JDK 1.8.0_91
*/
public class Price {
// 上下文对象,通常持有一个具体策略对象
private Strategy strategy;
public Price(Strategy strategy) {
this.strategy = strategy;
}
/**
* 用设计模式的解决方案
*/
public double quote(double goodPrice){
return this.strategy.calcPrice(goodPrice);
}
}
/** * 策略接口 * @author dy * @since 2016-08-10 & JDK 1.8.0_91 */ public interface Strategy { /** * 某算法接口 */ void algorithmInteface(); /** * 计算价格 * @param goodPrice * @return */ double calcPrice(double goodPrice); }
public class NormalCustomerStrategy implements Strategy { @Override public void algorithmInteface() { } @Override public double calcPrice(double goodPrice) { return goodPrice; } }
public class OldCustomerStrategy implements Strategy { @Override public void algorithmInteface() { } @Override public double calcPrice(double goodPrice) { return goodPrice*0.95; } }
public class BigCustomerStrategy implements Strategy { @Override public void algorithmInteface() { } @Override public double calcPrice(double goodPrice) { return goodPrice*0.90; } }
/** * @author dy * @since 2016-08-10 & JDK 1.8.0_91 */ public class Client { public static void main(String[] args) { double goodsPrice = 1000;//商品市场价 Strategy strategy = new BigCustomerStrategy();//商品策略 Price ctx = new Price(strategy);//上下文 System.out.println(ctx.quote(1000));//对应报价 } }
五:
策略模式的重心不是如何实现算法,而是如何组织、调用这些算法,从而使得程序结构更加灵活,具有更好的维护性和扩展性。