通过维护一个上下文管理器,实现某个方法的多种实现。
package strategy;
/**
* 策略上下文管理器.
* @author wwe
*
*/
public class Context {
private final Strategy s;
public Context(Strategy s) {
this.s = s;
}
/**
* 执行策略.
*/
public void excuteFunction() {
s.funciton();
}
}
package strategy;
/**
* 策略模式.
* @author wwe
*
*/
public interface Strategy {
/**
* 需要不同实现的方法(你懂的).
*/
public void funciton();
}
package strategy;
public class Strategy1 implements Strategy {
@Override
public void funciton() {
System.out.println("这是策略1");
}
}
package strategy;
public class Strategy2 implements Strategy {
@Override
public void funciton() {
System.out.println("这是策略2");
}
}
package strategy;
public class Client {
public static void main(String[] args) {
Strategy s1 = new Strategy1();
Strategy s2 = new Strategy2();
Context con1 = new Context(s1);
Context con2 = new Context(s2);
con1.excuteFunction();
con2.excuteFunction();
}
}
执行结果
这是策略1
这是策略2