java23中设计模式之策略模式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; /** * 负责和具体的策略类交互 * 这样的话,具体的算法和直接的客户端调用分离了,使得算法可以独立于客户端独立的变化。 * 如果使用spring的依赖注入功能,还可以通过配置文件,动态的注入不同策略对象,动态的切换不同的算法. * @author Administrator * */ public class Context { private Strategy strategy; //当前采用的算法对象 //可以通过构造器来注入 public Context(Strategy strategy) { super(); this.strategy = strategy; } //可以通过set方法来注入 public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void pringPrice(double s){ System.out.println("您该报价:"+strategy.getPrice(s)); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Strategy.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; public class NewCustomerFewStrategy implements Strategy { public double getPrice(double standardPrice) { System.out.println("不打折,原价"); return standardPrice; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; public class NewCustomerManyStrategy implements Strategy { public double getPrice(double standardPrice) { System.out.println("打九折"); return standardPrice*0.9; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; public class OldCustomerFewStrategy implements Strategy { public double getPrice(double standardPrice) { System.out.println("打八五折"); return standardPrice*0.85; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; public class OldCustomerManyStrategy implements Strategy { public double getPrice(double standardPrice) { System.out.println("打八折"); return standardPrice*0.8; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; public class Client { public static void main(String[] args) { Strategy s1 = new OldCustomerManyStrategy(); Context ctx = new Context(s1); ctx.pringPrice(998); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bjsxt.strategy; /** * 实现起来比较容易,符合一般开发人员的思路 * 假如,类型特别多,算法比较复杂时,整个条件语句的代码就变得很长,难于维护。 * 如果有新增类型,就需要频繁的修改此处的代码! * 不符合开闭原则! * @author Administrator * */ public class TestStrategy { public double getPrice(String type, double price) { if (type.equals("普通客户小批量")) { System.out.println("不打折,原价"); return price; } else if (type.equals("普通客户大批量")) { System.out.println("打九折"); return price * 0.9; } else if (type.equals("老客户小批量")) { System.out.println("打八五折"); return price * 0.85; } else if (type.equals("老客户大批量")) { System.out.println("打八折"); return price * 0.8; } return price; } }