您的位置:首页 > 编程语言 > Java开发

23种设计模式 第三部分 关系模式(1)策略模式

2016-08-24 23:34 531 查看




理解

策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下



图中ICalculator提供统一的方法,

AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:

首先统一接口:
public interface ICalculator {
public int calculate(String exp);
}


辅助类:

public abstract class AbstractCalculator {

public int[] split(String exp,String opt){
String array[] = exp.split(opt);
int arrayInt[] = new int[2];
arrayInt[0] = Integer.parseInt(array[0]);
arrayInt[1] = Integer.parseInt(array[1]);
return arrayInt;
}
}
三个实现类:

public class Plus extends AbstractCalculator implements ICalculator {

@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"\\+");
return arrayInt[0]+arrayInt[1];
}
}
public class Minus extends AbstractCalculator implements ICalculator {

@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"-");
return arrayInt[0]-arrayInt[1];
}

}
public class Multiply extends AbstractCalculator implements ICalculator {

@Override
public int calculate(String exp) {
int arrayInt[] = split(exp,"\\*");
return arrayInt[0]*arrayInt[1];
}
}
测试类

public class StrategyTest {

public static void main(String[] args) {
String exp = "2+8";
ICalculator cal = new Plus();
int result = cal.calculate(exp);
System.out.println(result);
}
}
输出:10

策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。

其他资料


Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
Capture the abstraction in an interface, bury implementation details in derived classes.


Example

A Strategy defines a set of algorithms that can be used interchangeably. Modes of transportation to an airport is an example of a Strategy. Several options exist such as driving one's own car, taking a taxi, an airport shuttle, a city bus, or a limousine service.
For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based
on trade-offs between cost, convenience, and time.



Define the interface of an interchangeable family of algorithms
Bury algorithm implementation details in derived classes
Derived classes could be implemented using the Template Method pattern
Clients of the algorithm couple themselves strictly to the interface

// 1. Define the interface of the algorithm
interface Strategy { public void solve(); }

// 2. Bury implementation
abstract class TemplateMethod1 implements Strategy { // 3. Template Method
public void solve() {
start();
while (nextTry() && ! isSolution())
;
stop();
}
protected abstract void    start();
protected abstract boolean nextTry();
protected abstract boolean isSolution();
protected abstract void    stop();
}

class Impl1 extends TemplateMethod1 {
private int state = 1;
protected void start() {
System.out.print( "start  " );
}
protected void stop() {
System.out.println( "stop" );
}
protected boolean nextTry() {
System.out.print( "nextTry-" + state++ + "  " );
return true;
}
protected boolean isSolution() {
System.out.print( "isSolution-" + (state == 3) + "  " );
return (state == 3);
}
}

// 2. Bury implementation
abstract class TemplateMethod2 implements Strategy { // 3. Template Method
public void solve() {
while (true) {
preProcess();
if (search()) break;
postProcess();
}
}
protected abstract void preProcess();
protected abstract boolean search();
protected abstract void postProcess();
}

class Impl2 extends TemplateMethod2 {
private int state = 1;
protected void    preProcess()  { System.out.print( "preProcess  " ); }
protected void    postProcess() { System.out.print( "postProcess  " ); }
protected boolean search() {
System.out.print( "search-" + state++ + "  " );
return state == 3 ? true : false;
}
}

// 4. Clients couple strictly to the interface
public class StrategyDemo {
public static void clientCode( Strategy strat ) {
strat.solve();
}
public static void main( String[] args ) {
Strategy[] algorithms = { new Impl1(), new Impl2() };
for (int i=0; i < algorithms.length; i++) {
clientCode( algorithms[i] );
}
}
}


Output:

start  nextTry-1  isSolution-false  nextTry-2  isSolution-true  stop
preProcess  search-1  postProcess  preProcess  search-2

https://sourcemaking.com/design_patterns/strategy/java/1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息