定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
package com.lyz.design.strategy;
/**
* Strategy
* @author binghe
*
*/
public abstract class Strategy {
public abstract void method();
}
package com.lyz.design.strategy;
/**
* ConcreteStrategy
* @author binghe
*
*/
public class StrategyImplA extends Strategy {
public void method() {
System.out.println("这是第一个实现");
}
}
StrategyImplB
package com.lyz.design.strategy;
/**
* ConcreteStrategy
* @author binghe
*
*/
public class StrategyImplB extends Strategy {
public void method() {
System.out.println("这是第二个实现");
}
}
StrategyImplC
package com.lyz.design.strategy;
/**
* ConcreteStrategy
* @author binghe
*
*/
public class StrategyImplC extends Strategy {
public void method() {
System.out.println("这是第三个实现");
}
}
package com.lyz.design.strategy;
/**
* Context
* @author binghe
*
*/
public class Context {
Strategy stra;
public Context(Strategy stra) {
this.stra = stra;
}
public void doMethod() {
stra.method();
}
}
package com.lyz.design.strategy;
/**
* Test
* @author binghe
*
*/
public class Test {
public static void main(String[] args) {
Context ctx = new Context(new StrategyImplA());
ctx.doMethod();
ctx = new Context(new StrategyImplB());
ctx.doMethod();
ctx = new Context(new StrategyImplC());
ctx.doMethod();
}
}