Design model of Shenkeng interview questions

This picture is from a unicorn company in Shenzhen

Design model of Shenkeng interview questions

When I see this topic, I think it's very interesting. Isn't it to remove if else if? Isn't this a typical strategy model? Of course, if else if cannot be completely eliminated by policy mode alone, and if can be eliminated by factory + policy mode

GOF I doubt that strategic patterns can eliminate some conditional statements in my book design patterns. As in the above example, although due to Context The policy implementation has been specified during initialization, and there is no need to select logical branches according to conditions in the calculation logic. However, the client code is initializing Context How to determine which policy implementation should be passed in? In fact, there is no lack of conditional judgment in the client code or elsewhere. Therefore, the elimination of conditional statements here is only for the conditional judgment of algorithm logic.

2. Advantages and disadvantages of strategy mode

So what are the advantages of the strategy model?

2.1 advantages

  1. Using the policy pattern, you can define a series of reusable behaviors and algorithms according to the policy interface;
  2. The caller only needs to hold the reference of context without knowing that the specific strategy implementation meets the Dimitri rule;
  3. context can do some general aspect logic outside the policy method

2.2 disadvantages

  1. The client code needs to know the different policies and how to select them. Therefore, you can see that the above client code has ugly conditional judgment;
  2. Since the policy class implements the same interface, the parameter list should be consistent, but not all policies need all parameters

3. The strategy mode is combined with the factory mode

For the first disadvantage. We can improve it through the combination of policy mode and factory mode. By further encapsulation, the conditional selection of client code is eliminated
The code is as follows

package com.zw.design.pattern.behavioral.mianshi;

/****
 * Define the interface implementation strategy of an animal class
 */
public interface IAnimalStrategy {

    public void doPromotion() ;
}
package com.zw.design.pattern.behavioral.mianshi;

/***
 * Define a cat class to implement the animal interface
 */
public class CatStrategy implements IAnimalStrategy {
    @Override
    public void doPromotion() {
        System.out.println("This is a cat class");
    }
}
package com.zw.design.pattern.behavioral.mianshi;

/***
 * Define a dog to implement the animal strategy interface
 */
public class DogStrategy implements IAnimalStrategy {
    @Override
    public void doPromotion() {
        System.out.println("handle dog behavior");
    }
}

package com.zw.design.pattern.behavioral.mianshi;

/***
 * Define an empty policy class to implement the animal policy interface
 */
public class EmptyAnimalStrategy implements IAnimalStrategy {
    @Override
    public void doPromotion() {

    }
}

package com.zw.design.pattern.behavioral.mianshi;

/***
 * This is the pig class that implements the animal policy interface class
 */
public class PigStrategy implements IAnimalStrategy {
    @Override
    public void doPromotion() {
        System.out.println("This is pig Class of");
    }
}

package com.zw.design.pattern.behavioral.mianshi;

import java.util.HashMap;
import java.util.Map;
//This is an abstract factory used to produce all classes that have implemented policy patterns
public abstract class AnimalStrategyFactory {

    //Define a static constant map collection
    private final static Map<String, IAnimalStrategy> PROMOTION_STRATEGY_MAP = new HashMap<String, IAnimalStrategy>();

    //Define three constants, which are final and have grouping function
    private interface PromotionKey{
        String DOG = "dog";
        String PIG = "pig";
        String CAT = "cat";
    }


    /***
     * Return a specific promotion class according to the key you passed in to realize extensibility
     * @param promotionKey
     * @return
     */
    public static IAnimalStrategy getPromotionStrategy(String promotionKey){
        IAnimalStrategy promotionStrategy = PROMOTION_STRATEGY_MAP.get(promotionKey);
        // return promotionStrategy == null ? null : promotionStrategy;
        //For a more business friendly mode, null cannot be returned here, so a class without promotional activities is defined
        return promotionStrategy == null ? NON_PROMOTION : promotionStrategy;
    }
    //Define an activity class without promotion
    private static final IAnimalStrategy NON_PROMOTION = new EmptyAnimalStrategy();

    //Use static code blocks to put values into the map and the values of specific policies
    static {
        PROMOTION_STRATEGY_MAP.put(PromotionKey.CAT,new CatStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.DOG,new DogStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.PIG,new PigStrategy());
    }
}

package com.zw.design.pattern.behavioral.mianshi;

/***
 * Clients using policy mode 
 */
public class AnimalActivity {
    //Put it into the specific class of animal strategy, and throw in the idea of interface polymorphism
    private IAnimalStrategy promotionStrategy;

    public AnimalActivity(IAnimalStrategy promotionStrategy){

        this.promotionStrategy = promotionStrategy;
    }
    //There is a specific behavior
    public void executePromotionStrategy(){
        promotionStrategy.doPromotion();
    }

}
//test
public static void main(String[] args) {
        String petType="dog";
        AnimalActivity animalActivity=new AnimalActivity(
                AnimalStrategyFactory.getPromotionStrategy(petType)
        );
        animalActivity.executePromotionStrategy();
    }

4. Applicable scenarios of strategy mode

When there are many behaviors or algorithms with different logic but belonging to the same type, you can consider using the policy pattern. In order to eliminate the conditional judgment in your algorithm code. At the same time, let your code meet a variety of design principles.

Many times, factory mode and strategy mode can solve similar problems for you. But you should think clearly whether you want an object or just a calculation result. If you need an object and want to do a lot of things with it. Then use factory mode. If you only want the calculation result of a specific algorithm, please use the policy mode.

The policy pattern belongs to the object behavior pattern, while the factory belongs to the creation pattern. The comparison between strategy mode and factory mode is as follows:

5. Summary

The problem solved by policy pattern is how to encapsulate reusable algorithms or behaviors. The strategy model meets the principles of single responsibility, opening and closing, Dimitri's law, inversion of dependence and so on. We must figure out the applicable scenario of the strategic mode, otherwise you will not know whether to use the factory mode or the strategic mode at some time. Finally, I remind you that design patterns are often mixed. We should not be limited to using a certain design pattern to solve problems.

Keywords: Java Design Pattern Interview

Added by superhaggis on Mon, 29 Nov 2021 05:33:46 +0200