策略模式 Strategy

public Context(String strategyType)

{

switch(strategyType)

{

case "算法A":

     strategy=new ContextStrategyA();

     break;

case "算法B":

     strategy=new ContextStrategyB();

     break;

...............

}

}

DF对策略模式的定义是这样的:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化不会影响到使用算法的客户(main函数)。

abstract class Strategy

{

public abstract void AlgorithmInterface();

}
class ConcreteStratrgyA extends Strategy

{

 @override

public void AlgorithmInterface()

{

   //算法A的具体实现。

}

}
class ConcreteStrategyB extends Strategy

{

 @override

public void AlgorithmInterface()

{

  //算法B的具体实现

}

}
class Context

{

Strategy strategy;

public Context(Strategy strategy)

{

this.strategy=strategy;

}

public void ContextInterface)

{

strategy.AlgorithmInterface();

}

}

在Context类的构造方法中可以使用简单工厂模式,实现策略模式和简单工厂模式的结合。

public static void main(String[] args)

{

Context context;

context=new Context(new ContextStrategyA());

context.ContextInterface();



context=new Context(new ContextStrategyB());

context.ContextInterface();

}
原文地址:https://www.cnblogs.com/wangjiyuan/p/Strategy.html