它也属于行为型模式的一种,在这种模式下,一个类的行为或其算法可以在运行时更改。简单实现
环境类(对外提供统一接口)
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int request(int req) {
return state.doAction(req);
}
}
策略接口
interface Strategy {
int doAction(int req);
}
具体策略
public class AddStrategy implements Strategy{
@Override
public int doAction(int req) {
return req + req;
}
}
public class MultiStrategy implements Strategy{
@Override
public int doAction(int req) {
return req * req;
}
}
测试类
public static void main(String[] args) {
Strategy strategy= new Strategy();
strategy.setStrategy(new AddStrategy ());
System.out.println(context.request(10));
strategy.setStrategy(new MultiStrategy ());
System.out.println(context.request(10));
}