创建一个能够根据所传递的参数对象的不同而具有不同行为的方法,就称为策略模式。
这类方法包含索要执行的算法中固定不变的部分,而“策略”包含变化的部分。策略就是传递进去的参数对象,它包含要执行的代码。
概括来说就是,一个问题有好多种解法,我们选择其中一种就可以。
优点:
if-else语句来完成此类操作,但是这种情况耦合度太高,且代码臃肿,策略模式可以避免这种情况。缺点:
《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