策略模式: 定义了不同的算法, 分别分装起来, 让他们可以互相替换, 即使算法变化了, 也不会影响到使用算法的用户
首先定义一个抽象算法类, 有两个类继承了这个抽象类, 重写了 AlgorithmInterface()方法
- public abstract class Strategy {
- public abstract void AlgorithmInterface();
- }
- public class AlgorithmA extends Strategy {
- @Override
- public void AlgorithmInterface() {
- System.out.println("实现算法 A");
- }
- }
- public class AlgorithmB extends Strategy {
- @Override
- public void AlgorithmInterface() {
- System.out.println("实现算法 B");
- }
- }
用一个 context 类来维护对抽象算法类 Strategy 对象的引用(重点)
- public class Context {
- Strategy strategy;
- public Context(Strategy strategy){
- this.strategy = strategy;
- }
- public void ContrxtInterface(){
- strategy.AlgorithmInterface();
- }
- }
测试类 1
- public class Test1 {
- public static void main(String[] args) {
- Context context = null;
- context = new Context(new AlgorithmA());
- context.ContrxtInterface();
- context = new Context(new AlgorithmB());
- context.ContrxtInterface();
- }
- }
但是从上面测试类 1 的代码我们发现是在客户端判断是用什么算法, 现在我们想把这个判断交由其他类处理, 于是就有了下面的策略模式与简单工厂结合的方法.
- public class Context2 {
- Strategy strategy = null;
- public Context2(String type){
- switch (type){
- case "A": strategy = new AlgorithmA();
- break;
- case "B": strategy = new AlgorithmB();
- break;
- }
- }
- public void ContrxtInterface(){
- strategy.AlgorithmInterface();
- }
- }
测试类 2
- public class Text2 {
- public static void main(String[] args) {
- Context2 context2A = new Context2("A");
- context2A.ContrxtInterface();
- Context2 context2B = new Context2("B");
- context2B.ContrxtInterface();
- }
- }
结论: 策略模式定义一系列算法, 他们完成的都是同一件事, 只是实现方法不同, 比如超市收银时, 会员打折, 非会员不打折, 实现的都是收钱, 实现方法 (打折 / 非打折) 不同.
优点: 1. 上下文和具体策略是松耦合关系. 因此上下文只知道它要使用某一个实现 Strategy 接口类的实例, 但不需要知道具体是哪一个类.
2. 策略模式满足 "开 - 闭原则". 当增加新的具体策略时, 不需要修改上下文类的代码, 上下文就可以引用新的具体策略的实例.
来源: http://www.bubuko.com/infodetail-3098844.html