策略模式:它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化不会影响到使用算法的客户。
这个模式涉及到三个角色:
环境(Context)角色:用ConcreteStrategy来配置,持有一个Strategy的引用。
抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。继承Strategy。
下面的场景是商场中卖商品的场景,可能打折,可能满多少减现金。
抽象角色:
public interface PriceStrategy {
Double calPrice(Double rignPrice);
}
具体角色A:
public class GoodsA implements PriceStrategy {
@Override
public Double calPrice(Double rignPrice) {
return rignPrice*0.9;//商品打9折
}
}
具体角色B:
public class GoodsB implements PriceStrategy{
@Override
public Double calPrice(Double rignPrice) {
if(rignPrice>=300){//满300减100
return rignPrice-100;
}else{
return rignPrice;
}
}
}
具体角色C:
public class GoodsC implements PriceStrategy {
@Override
public Double calPrice(Double rignPrice) {
return rignPrice;//原价返回
}
}
环境角色:
public class Context {
PriceStrategy priceStrategy;
Context(PriceStrategy priceStrategy){
this.priceStrategy=priceStrategy;
}
public void ContextInterface(Double rignPrice){
System.out.println(priceStrategy.calPrice(rignPrice));
}
}
测试:
public class TestStrategy {
public static void main(String args[]){
Context context;
context=new Context(new GoodsA());
context.ContextInterface(300.0);
context=new Context(new GoodsB());
context.ContextInterface(300.0);
context=new Context(new GoodsC());
context.ContextInterface(300.0);
}
}
这是结尾。。。