策略模式

策略模式

创建一个能够根据所传递的参数对象的不同而具有不同行为的方法,就称为策略模式。

这类方法包含索要执行的算法中固定不变的部分,而“策略”包含变化的部分。策略就是传递进去的参数对象,它包含要执行的代码。

概括来说就是,一个问题有好多种解法,我们选择其中一种就可以。


优缺点

优点:

  1. 正常情况下我们往往会使用 if-else语句来完成此类操作,但是这种情况耦合度太高,且代码臃肿,策略模式可以避免这种情况。
  2. 策略模式遵循开闭原则,实现代码解耦。扩展新方法时,会比较方便,只需要继承策略接口就可以。

缺点:

  1. 客户端必须知道所有的策略类,并自行决定使用哪一个策略。
  2. 策略模式会出现很多的策略类。
  3. context 在使用策略类的时候,策略类由于继承了策略接口,所以有些策略可能会用不到,但是依然会被初始化。

《Think In Java》中的例子:

class Processor {
    public String name() {
        return getClass.getSimpleName();
    }
    Object process(Object input) {
        return input;
    }
}

class Upcase extends Processor {
    String process(Object input) {
        return ((String) input).toUpperCase();
    }
}

class DownCase extends Processor {
    String process(Object input) {
        return ((String) input).toLowerCase();
    }
}

public class Apply {
    public static void process(Processor p, Object s){
        print("Using Processor " + p.name());
        print(p.process(s));
    }
    public static void main(String[] args){
        String s = "Disagreement with beliefs is by definition incorrect";
        process(new Upcase(), s);
        process(new Downcase(), s);
    }
}
/* Output
Using Processor Upcase
DISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECT
Using Processor Downcase
disagreement with beliefs is by definition incorrect
*/

example:

public interface Travel{
    public void travelStyle();
}

class ShipStrategy implements Travel {
    public void travelStyle() {
        System.out.println("ship");
    }
}

class AirStrategy implements Travel {
    public void travelStyle() {
        System.out.println("air");
    }
}

class TrainStrategy implements Travel {
    public void travelStyle() {
        System.out.println("train");
    }
}

class Traveler {
    public void toTravel(Travel travel) {
        travel.travelStyle();
    }
}

public class StrategyPattern {

    public static void main(String[] args) {
        Traveler traveler = new Traveler();
        traveler.toTravel(new AirStrategy());
        traveler.toTravel(new ShipStrategy());
        traveler.toTravel(new TrainStrategy());
    }
}

原文地址:https://www.cnblogs.com/wulaa/p/13179064.html