策略模式 (Strategy Pattern)
定义
它是将定义的算法家族、分别封装起来,让它们之间可以相互替换,从而让算法的变化不会影响到使用算法的用户。
可以避免多重分支的 if-else、switch语句。
属于行为型模式。
适用场景
- 如果系统中有很多类,而他们的区别仅在于它们的行为不同。
- 一个系统需要动态地在几种算法中选择一种。
- 需要屏蔽算法规则。
标准示例
IStrategy:策略抽象类
public interface IStrategy{void algorithm()
}
ConcreteStrategyA:具体策略A
public class ConcreteStrategyA implements IStrategy{public void algorithm(){System.out.println("Strategy A");}
}
ConcreteB: 具体策略B
public class ConcreteStrategyB implements IStrategy{public void algorithm(){System.out.println("Strategy B");}
}
Context:上下文,用来操作策略的决策层面,会开放给客户端。
public class Context{private IStrategy strategy;public Context(IStrategy strategy){this.strategy = strategy;}public void algorithm(){strategy.algorithm();}
}
ClientTest
public class ClientTest{public static void main(String[] args){//选择具体策略IStrategy strategy = new ConcreteStrategyA();//上下文Context context = new Context(strategy);//执行上下文的算法context.algorithm(); }
}
策略模式封装了算法,在实际中,各种电商的优惠活动,经常会有不同的计算方法。我们就通过一个优惠的例子来看一下,策略模式的应用。
我们先提供一个抽象的优惠策略类 PromotionStrategy
然后创建4个优惠策略实现类:
CouponStrategy
、GroupBuyStrategy
、CashRefundStrategy
、DefaultStrategy
最后,通过 策略的上下文,来实现策略的调用:StrategyContext
public abstract class PromotionStrategy {abstract void promotionCalculate();
}
public class CouponStrategy extends PromotionStrategy{void promotionCalculate() {System.out.println("coupon strategy ...");}
}
public class GroupBuyStrategy extends PromotionStrategy{void promotionCalculate() {System.out.println("group buy strategy ...");}
}
public class CashRefundStrategy extends PromotionStrategy{void promotionCalculate() {System.out.println("cash refund strategy...");}
}
public class DefaultStrategy extends PromotionStrategy{void promotionCalculate() {System.out.println("default strategy ...");}
}
public class StrategyContext {private static Map<String, PromotionStrategy> PROMOTIONS = new HashMap<String, PromotionStrategy>();//对算法进行了封装static {PROMOTIONS.put("COUPON", new CouponStrategy());PROMOTIONS.put("GROUPBUY", new GroupBuyStrategy());PROMOTIONS.put("CASHREFUND", new CashRefundStrategy());}//使得调用方通过传入String,即可选择相应的算法public PromotionStrategy getPromotion(String promotion) {PromotionStrategy strategy = PROMOTIONS.get(promotion);return strategy == null ? new DefaultStrategy() : strategy;}
}
客户端调用类:
public class ClientTest {public static void main(String[] args) {StrategyContext context = new StrategyContext();PromotionStrategy strategy = context.getPromotion("COUPON");strategy.promotionCalculate();}
}
输出结果:
coupon strategy ...
以上就是策略模式的全部内容,感谢阅读。