java design pattern-policy pattern

Noun interpretation

Strategy Pattern

Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the changes of algorithms to not affect the users who use them.

Application scenario

  • There are many classes in the system, and the only difference between them is that they behave differently.
  • A system needs to dynamically select one of several algorithms

Writing method

The writing of policy pattern is very simple. In fact, it is to define an interface first, and then let different algorithms implement the interface separately, so that in the place of calling the algorithm, we can directly select different algorithm implementation classes.

Usually our algorithm selection is singleton type. We can consider using enumeration to make selection. This is a very elegant way, for example:

 * Selection of Strategic Approaches through Enumeration
public enum EnumPromotionFactory  {

    COUPON(new CouponStrategy()),
    CASHBACK(new CashbackStrategy()),

    private PromotionStrategy strategy ;

    public PromotionStrategy getStrategy() {
        return strategy;

    private  EnumPromotionFactory(PromotionStrategy strategy){
        this.strategy = strategy;


In addition, it can be distinguished directly by character creation, such as:

 * Promotion Strategy Factory
public class PromotionStrategyFactory {
    private static Map<String,PromotionStrategy> PROMOTION_STRATEGY_MAP = new HashMap<String, PromotionStrategy>();
    static {
        PROMOTION_STRATEGY_MAP.put(PromotionKey.COUPON,new CouponStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.CASHBACK,new CashbackStrategy());

    private static final PromotionStrategy NON_PROMOTION = new EmptyStrategy();

    private PromotionStrategyFactory(){}

    public static PromotionStrategy getPromotionStrategy(String promotionKey){
        PromotionStrategy promotionStrategy = PROMOTION_STRATEGY_MAP.get(promotionKey);
        return promotionStrategy == null ? NON_PROMOTION : promotionStrategy;

    private interface PromotionKey{
        String COUPON = "COUPON";
        String CASHBACK = "CASHBACK";

Examples of application


  • Comparator interface comparison () method


  • Resource
  • InstantiationStrategy

Little knowledge

In practical applications, multiple strategies can also be inherited from each other.

Tags: JDK Spring

Posted on Tue, 01 Oct 2019 21:12:29 -0400 by newb