首页 > 其他 > 详细

策略模式

时间:2020-01-17 02:35:59      阅读:122      评论:0      收藏:0      [点我收藏+]

个人博客

http://www.milovetingting.cn

策略模式

模式介绍

实现某一个功能有多种算法或者策略,可以根据实际情况选择不同的算法或者策略来实现该功能,如果将这些算法或者策略抽象出来,提供一个统一的接口,不同的算法或策略有不同的实现类,这样在程序客户端就可以通过注入不同的实现对象来实现算法或者策略的动态替换,这种模式的可扩展性,可维护性更高。这就是策略模式。

模式定义

策略模式定义了一系列的算法,并将每一个算法封装起来,使他们可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

使用场景

  1. 针对同一类型问题的多种处理方式,仅仅是具体行为有差别时

  2. 需要安全地封装多种同一类型的操作时

  3. 出现同一抽象类有多个子类,而又需要使用if-else或者switch-case来选择具体子类时。

定义策略接口类

public interface Strategy {
    
    int calc();

}

定义具体的策略实现类

public class Strategy1 implements Strategy {

    @Override
    public int calc() {
        System.out.println("Strategy1");
        return 1;
    }

}

public class Strategy2 implements Strategy {

    @Override
    public int calc() {
        System.out.println("Strategy2");
        return 2;
    }

}

增加一个策略管理类

public class StrategyManager {

    private Strategy mStrategy;

    public void setStrategy(Strategy strategy) {
        this.mStrategy = strategy;
    }

    public int calc() {
        return mStrategy.calc();
    }

}

通过setStrategy,可以动态替换具体的策略类

在客户端中调用

public static void main(String[] args) {
        StrategyManager manager = new StrategyManager();
        Strategy strategy1 = new Strategy1();
        manager.setStrategy(strategy1);
        manager.calc();
        Strategy strategy2 = new Strategy2();
        manager.setStrategy(strategy2);
        manager.calc();
    }

输出结果

Strategy1
Strategy2

依次执行了策略1和策略2。

小结

策略模式主要用来分离算法,在相同的行为抽象下有不同的具体实现策略。策略模式很好地演示了开闭原则,也就是定义抽象,注入不同的实现,从而达到很好的可扩展性。

策略模式

原文:https://www.cnblogs.com/milovetingting/p/12203784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!