策略模式就是定义一系列的算法,把他们一个一个封装起来,并使他们可以相互替换。也就是实现算法和调用端的解耦,他的核心并不是如何实现算法而是如何组织,调用这些算法。下面是个demo:
package com.jerry.design.strategy;
// 测试类
public class Test {
public static void main(String[] args) {
ConcreteStrategyA concreteStrategyA = new ConcreteStrategyA();
Context context = new Context(concreteStrategyA);
context.doSomething();
}
}
interface Strategy {
public void doSomething();
}
class ConcreteStrategyA implements Strategy{
@Override
public void doSomething() {
System.out.println("ConcreteStrategyA的doSomething()");
}
}
class ConcreteStrategyB implements Strategy{
@Override
public void doSomething() {
System.out.println("ConcreteStrategyB的doSomething()");
}
}
class Context{
private Strategy strategy;
public Context(Strategy strategy) {
super();
this.strategy = strategy;
}
public void doSomething(){
strategy.doSomething();
}
}