1.策略模式
将每一个算法封装到具有共同接口的独立类中,客户端自行决定使用 哪一个策略。
2.示例
public interface Strategy
{
public void calculate();
}
public class StrategyA implements Strategy
{
@Override
public void calculate()
{
System.out.println("A算法。。。");
}
}
public class StrategyB implements Strategy
{
@Override
public void calculate()
{
System.out.println("B算法。。。");
}
}
public class Context
{
private Strategy strategy;
public Context(Strategy strategy)
{
this.strategy = strategy;
}
public void startCalculate()
{
this.strategy.calculate();
}
}
public class StrategyTest
{
public static void main(String[] args)
{
Strategy strategyA = new StrategyA();
Strategy strategyB = new StrategyB();
Context context = new Context(strategyA);
context.startCalculate();
context = new Context(strategyB);
context.startCalculate();
}
}