策略模式
2017-08-15 本文已影响10人
ilaoke
Define a family of algorithms, encapsulate each one, and make them interchangeable. The strategy pattern lets the algorithm vary independently from client to client.
策略模式的核心就是:在运行时动态选择使用哪种策略,实现策略,选择策略。
策略接口
/**
* 策略接口
*/
public interface IStrategy {
void solve();
}
策略一
/**
* 策略1抽象类
*/
public abstract class AbstractStrategyOne implements IStrategy {
/**
* 具体策略的实现是模板方法
*/
@Override
public void solve() {
start();
while (nextTry() && !isSolution()) {
// do something
}
stop();
}
abstract void start();
abstract boolean nextTry();
abstract boolean isSolution();
abstract void stop();
}
public class StrategyOne extends AbstractStrategyOne {
private int state = 0;
@Override
void start() {
System.out.println("start");
}
@Override
boolean nextTry() {
System.out.println("NextTry-" + state++);
return true;
}
@Override
boolean isSolution() {
System.out.println("IsSolution-" + (state == 3) + " ");
return (state == 3);
}
@Override
void stop() {
System.out.println("stop");
}
}
策略二
/**
* 策略2抽象类
*/
public abstract class AbstractStrategyTwo implements IStrategy {
/**
* 具体策略的实现是模板方法
*/
@Override
public void solve() {
while (true) {
preProcess();
if (search()) {
break;
}
postProcess();
}
}
abstract void preProcess();
abstract boolean search();
abstract void postProcess();
}
public class StrategyTwo extends AbstractStrategyTwo {
private int state = 0;
@Override
void preProcess() {
System.out.println("PreProcess ");
}
@Override
boolean search() {
System.out.println("Search-" + state++ + " ");
return state == 3;
}
@Override
void postProcess() {
System.out.println("PostProcess ");
}
}
执行
public class Test {
private static void execute(IStrategy strategy) {
strategy.solve();
}
public static void main(String[] args) {
/**
* 控制使用哪种策略
*/
IStrategy[] algorithms = {new StrategyOne(), new StrategyTwo()};
for (IStrategy algorithm : algorithms) {
execute(algorithm);
}
}
}