定义
策略模式(Strategy):策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。
类图
代码
Strategy策略模式定义方法的抽象类
package ding.study.designpatterns.strategy;
/**
* 策略模式定义方法的抽象类
*
* @author daniel
*
*/
abstract class Strategy {
public abstract void AlgorithmInterface();
}
ConcreteStrategyA 策略实现类
package ding.study.designpatterns.strategy;
/**
* 继承抽象类 实现抽象方法
*
* @author daniel
*
*/
class ConcreteStrategyA extends Strategy {
public void AlgorithmInterface() {
System.out.println("算法A实现");
}
}
class ConcreteStrategyB extends Strategy {
public void AlgorithmInterface() {
System.out.println("算法B实现");
}
}
class ConcreteStrategyC extends Strategy {
public void AlgorithmInterface() {
System.out.println("算法C实现");
}
}
Context维护Strategy对象的引用
package ding.study.designpatterns.strategy;
/**
*
* @author daniel 维护Strategy对象的引用
*/
class Context {
Strategy strategy;
/**
* 初始化抽象类
*
* @param strategy
*/
public Context(Strategy strategy) {
this.strategy = strategy;
}
/**
* 调用算法 实现方法
*/
public void ContextInterface() {
strategy.AlgorithmInterface();
}
}
TestMain测试类
package ding.study.designpatterns.strategy;
/**
* PS:策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。
策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或行为。继承有助于析取出些算法中的公共功能。
简化了单元测试,每个类可以通过自己的接口测试。
-------------------------------------------------------------------------------------------
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-17 上午10:14:59
*/
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
Context context;
context= new Context(new ConcreteStrategyA());
context.ContextInterface();
context= new Context(new ConcreteStrategyB());
context.ContextInterface();
context= new Context(new ConcreteStrategyC());
context.ContextInterface();
}
}
源码:
https://github.com/dingsai88/StudyTest/tree/master/src/ding/study/designpatterns/strategy