策略模式对应于解决某一个问题的一个算法族, 允许用户从该算法族中任选一种算法解决某一问题; 同时, 可以方便的更换算法或增加新的算法; 并且由客户决定调用哪个算法.
1, 提出问题: 实现一个根据客户类型获取商品价格的方法, 如下:
- public class strategyDemo1
- {
- public double getPrice(String type, double price)
- {
- if("普通客户小批量".equals(type))
- {
- System.out.println("不打折, 原价");
- return price;
- }
- else if ("普通客户大批量".equals(type))
- {
- System.out.println("打九折");
- return price * 0.9;
- }
- else if ("老客户小批量".equals(type))
- {
- System.out.println("打八五折");
- return price * 0.85;
- }
- else if ("老客户大批量".equals(type))
- {
- System.out.println("打八折");
- return price * 0.8;
- }
- else
- {
- return price;
- }
- }
- }
以上的实现比较基础, 能够解决我们的问题, 但是存在以下几个问题:
(1) 若类型比较多, 实现复杂时, 整个条件语句的代码就变得特别长, 难于维护;
(2) 若新增类型, 则需要频繁的修改代码, 这就违反了开闭原则;
2, 为了解决以上问题, 我们使用策略模式来实现;
策略模式的实现类图, 如下所示:
算法的接口 (Strategy), 如下所示:
- public interface Strategy
- {
- public double getPrice(double standardPrice);
- }
新客户小批量算法类 (NewCustomerFewStrategy ), 如下所示:
- public class NewCustomerFewStrategy implements Strategy
- {
- @Override
- public double getPrice(double standardPrice)
- {
- System.out.println("不打折");
- return standardPrice;
- }
- }
新客户大批量算法类 (NewCustomerManyStrategy ), 如下所示:
- public class NewCustomerManyStrategy implements Strategy
- {
- @Override
- public double getPrice(double standardPrice)
- {
- System.out.println("打九折");
- return standardPrice * 0.9;
- }
- }
老客户小批量算法类 (OldCustomerFewStrategy ), 如下所示:
- public class OldCustomerFewStrategy implements Strategy
- {
- @Override
- public double getPrice(double standardPrice)
- {
- System.out.println("打八五折");
- return standardPrice * 0.85;
- }
- }
老客户大批量算法类 (OldCustomerManyStrategy ), 如下所示:
- public class OldCustomerManyStrategy implements Strategy
- {
- @Override
- public double getPrice(double standardPrice)
- {
- System.out.println("打八折");
- return standardPrice * 0.8;
- }
- }
Context 实现类: 将算法和客户直接分离了, 使得算法可以独立于客户端的独立变化
- public class Context
- {
- private Strategy strategy; // 当前采用的算法
- // 使用构造器注入
- public Context(Strategy strategy)
- {
- this.strategy = strategy;
- }
- public void printPrice(double s)
- {
- System.out.println("您该报价:" + strategy.getPrice(s));
- }
- }
测试类, 如下所示:
- public class TestStrategy
- {
- public static void main(String[] args)
- {
- // 获取新客户大批量算法
- Strategy strategy = new NewCustomerManyStrategy();
- Context context = new Context(strategy);
- context.printPrice(1000);
- }
- }
结果如下:
打九折
您该报价: 900.0
来源: http://www.bubuko.com/infodetail-2876658.html