美文网首页
策略模式

策略模式

作者: 冉桓彬 | 来源:发表于2017-05-07 23:19 被阅读6次

1、策略模式:

在软件开发中常常遇到这样的情况: 实现某一个功能可以有多种算法或者策略, 我们根据实际情况选择不同的算法或者策略来完成该功能.
  针对这种情况, 一种常规的方法是将多种算法写在一个类中. 如果将这种算法或者策略抽象出来, 提供一个统一的接口, 不同的算法或者策略有不同的实现类, 这样在程序客户端就可以通过注入不同的实现对象来实现算法或者策略的动态替换, 这种模式的可扩展性、可维护性也就更高.

2、策略模式的定义:

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

3、策略模式的使用情景:

  • 1、针对同一类型问题的多种处理方式, 仅仅是具体行为有差别时;
  • 2、需要安全地封装多种同一类型的操作时;
  • 3、出现同一抽象类有多个子类, 而又需要使用if-else或者switch-case来选择具体子类时.

4、优缺点:

1、优点:
  • 1、结构清晰明了, 使用简单直观;
  • 2、耦合度相对而言较低, 扩展方便;
  • 3、操作封装也更为彻底, 数据更为安全;
2、缺点:
  • 随着策略的增加, 子类也会变得繁多;

5、策略模式的简单实现:

public interface CalculaeStrategy {
    int calculaePrice(int km);
}

public class BusStrategy implements CalculaeStrategy {
    @Override
    public int calculaePrice(int km) {
        if(km < 3) {
            return 3;
        } else if (km < 4) {
            return 4;
        } else if (km < 5) {
            return 5;   
        } else {
            return 6;
        } 
    }
}

public class CarStrategy implements CalculaeStrategy {
    @Override
    public int calculaePrice(int km) {
        if (km < 4) {
            return 5;
        } else if (km < 5) {
            return 6;
        }else {
            return 7;
        }
    }
}

public class Test {

    private CalculaeStrategy mStrategy;

    public static void main(String[] args) {
        Test t = new Test();
        t.setStrategy(new CarStrategy());
        t.calculaePrice(10);
    }

    public void setStrategy(CalculaeStrategy strategy) {
        mStrategy = strategy;
    }

    public int calculaePrice(int km) {
        return mStrategy.calculaePrice(km);
    }
}

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/tbpptxtx.html