Strategy模式也叫策略模式是行为模式之一,它对一系列的算法加以封装,为所有算法定义一
个抽象的算法接口,并通过继承该抽象算法接口对所有的算法加以封装和实现,具体的算法选择交由客户端决定(策略)。Strategy模式主要用来平滑地处理算法的切换 。Strategy:策略(算法)抽象package com.org.strategy;public interface Strategy { public double cost(double num);}ConcreteStrategy:各种策略(算法)的具体实现。package com.org.strategy;public class StrategyA implements Strategy{ public double cost(double num) { return num * 0.8; }}package com.org.strategy;public class StrategyB implements Strategy { public double cost(double num) { if(num >= 200) { return num - 50; } return num; }}Context:策略的外部封装类,或者说策略的容器类。根据不同策略执行不同的行为。策略由外部环境决定。 package com.org.strategy;public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public double cost(double num){ return this.strategy.cost(num); } }客户端代码:package com.org.strategy;public class MainClass { public static void main(String[] args) { double num = 200; Context context = new Context(new StrategyB()); double newNum = context.cost(num); System.out.println("price" + newNum); }}