设计模式之策略模式

79 阅读1分钟

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

当某个方法要执行某个操作,但是这个操作会根据不同的情况有不同的变化。比如说我们实现一个方法,这个方法模拟从甲地到乙地的过程。我们可以选择汽车、飞机、火车、轮船等等方式,根据不同的天气情况我们选择不同的方式。假如我们使用if else编码可能会有如下代码:

    public void travel(Weather weather) {
        // 假如是晴天采用某种方式
        if (weather.getInfo().equals("晴天")) {

        } else if (weather.getInfo().equals("雨天")) { // 雨天

        } else if (weather.getInfo().equals("...")) { // 其他情况...

        }
        ...
    }

当我们采用这种方式时,如果以后要改变某种天气情况下的出行方式,或者要增加新的交通方式,对于这样的代码就不易维护。

像这样的情况,更好的方式是使用策略模式。

先定义一个旅行交通方式策略接口:

    public interface TravelStrategy {
        void execute(Weather weather);
    }

将travel方法改为如下形式:

    public void travel(Weather weather, TravelStrategy strategy) {
        strategy.execute(weather);
    }

这样可以传入不同的策略实现类,就能采用不同的方式了。