概念
结构
案例代码
定义一个促销活动共同接口
public interface Strategy {
void show();
}
定义具体策略角色
public class StrategyA implements Strategy{
@Override
public void show() {
System.out.println("买一送一");
}
}
public class StrategyB implements Strategy{
@Override
public void show() {
System.out.println("满200送50");
}
}
定义环境角色(context) 联系上下文
public class SaleMan {
private Strategy strategy;
public SaleMan(Strategy strategy){
this.strategy = strategy;
}
public void sale(){
strategy.show();
}
}
根据传进来的策略对象来实现不同的策略方法
public class Test {
public static void main(String[] args) {
StrategyA strategyA = new StrategyA();
SaleMan saleMan = new SaleMan(strategyA);
saleMan.sale();
//切换B策略
saleMan.setStrategy(new StrategyB());
saleMan.sale();
}
}