👉 Design mode directory

What is Strategy Mode?

concept

Strategy pattern is a behavioral pattern. Definition: This pattern defines a series of algorithms and encapsulates each algorithm so that they can be replaced with each other, and the changes in the algorithm will not affect the customers who use the algorithm. In simple terms, is to write the original inside the class algorithm and can replace each other algorithm to extract algorithm class, all of these algorithms classes like one trick, then objects by using different algorithms to realize the algorithm to replace, as to why is algorithm, I think actually business also line, but with the business is not very strong, in many cases is not applicable.

The strategy pattern is to reuse code in a way that inheritance can’t, and to reuse code in both landscape and vertical, and only in vertical if inheritance is used. I have seen a lot of blog articles write that strategy mode is used to reduce if-else, and I have not experienced how to reduce if-else in the process of learning, so I will not think about this aspect, and I will add something later when I have a change.

For example, there are many kinds of sorting algorithms, bubble, select, merge, insert, binary tree, etc., and we can use one of them every time we sort, so if we create N algorithms in a class, the class will explode; There is also the supermarket membership system, for example, the first-level members do not have any privileges but points, the second-level members can have membership price and points, the third-level members not only have membership price and double points, if the strategy mode is not adopted, then there will be a lot of repeated code, using inheritance can not solve this problem.

advantages

  1. It conforms to the principle of openness and closure. If you want to add a new algorithm, you can directly write a new algorithm class, without modifying the existing class, which improves the scalability of the system.
  2. Consistent with the single responsibility principle. Encapsulate the algorithm into a single class that only does what the algorithm does.
  3. Improved code reuse.

disadvantages

  1. There will be a large number of policy classes, which makes maintenance difficult.
  2. Consumers need to understand the differences between each policy class and choose one based on their own needs.

The principle of

“+” means compliance, and “-” means noncompliance or irrelevant

The principle of Open the closed Single responsibility Di milt Replacement on the Richter scale Dependency inversion Interface segregation Synthesis of reuse
+ + +

Applicable scenario

  1. Inheritance does not allow reuse of the current code. Inheritance can only reuse code vertically, and applicable policy classes can reuse code horizontally as well as vertically.
  2. There are situations where the algorithm needs to switch frequently.
  3. Multiple algorithm implementations are too complex.

How to implement

To implement the strategy pattern, you need three things:

  1. Policy abstract class/interface: Defines the public interface of the policy class, specifies the responsibility of the policy class, and uses the abstract class or interface when declaring references.
  2. Policy implementation class: the implementation of policy abstract class/interface, the implementation of concrete algorithms.
  3. Environment class: Manages and invokes policy implementation class objects.

The class diagram

example

Here in supermarket member of the example above, for example, do not have any privilege level only integral, secondary can have member price and integral, level 3 is not only the member price and double integral, if it’s not the strategy pattern, then to realize the three classes, which the member price and integral processing logic is to be repeated and the code also can’t get reuse.

Then there are three kinds of objects: members, price treatment methods and integral treatment methods. Members correspond to the environment category, while price and integral treatment methods correspond to the strategy category. Price treatment methods: no treatment, member price, integral treatment methods: integral, double integral

The class diagram

code

/ * * * *@author xuxiaobai
 */
public class StrategyTest {
    
    public static void main(String[] args) {
        System.out.println("---- First-class member ----");
        Member member1 = new Member("111");
        member1.doProcess(100);
        System.out.println("---- Level 2 member ----");
        Member member2 = new Member("222");
        member2.doProcess(100);
        System.out.println("---- Third-level member ----");
        Member member3 = new Member("333");
        member3.doProcess(100);
        /** * Result: * ---- level 1 member ---- * Need to pay :100.0 yuan * Paid successfully! * User: 111, add points: 100 * ---- Second level member ---- * Need to pay :90.0 yuan * Successful payment! * User: 222, add points: 100 * ---- Level 3 member ---- * Need to pay :90.0 yuan * Successful payment! * User: 333, increased credits: 200 */}}/** * Policy interface * Price processing interface */
interface Price{
    /** * Processing price *@param price
     * @return* /
    double processPrice(double price);

}

/** * Policy class * no processing price class */
class CommonPrice implements Price{
    @Override
    public double processPrice(double price) {
        returnprice; }}/** * Strategy * Membership price */
class MemberPrice implements Price{
    @Override
    public double processPrice(double price) {
        // I want to be a dirty business
        return price>100? price-5:price*0.9; }}/** * Policy interface * Integral processing interface */
interface Integral{
    /** * increase the integral *@param integral
     */
    long processIntegral(long integral);

}

/** * Strategy class * integral class */
class CommonIntegral implements Integral{

    @Override
    public long processIntegral(long price) {
        returnprice; }}class DoubleIntegral implements Integral{

    @Override
    public long processIntegral(long price) {
        return price*2; }}/** * Environmental category * member */
class Member{

    private String phone;

    private Price priceStrategy;

    private Integral integralStrategy;

    / * * * *@param phone
     */
    public Member(String phone){
        this.phone=phone;
        /** The simulation goes to the database to query the membership level, and then assigns the price and points processing strategy ** this is similar to a factory method, using different strategies with different results */
        if ("111".equals(phone)){
            // Level 1 member
            this.priceStrategy=new CommonPrice();
            this.integralStrategy=new CommonIntegral();
        }
        if ("222".equals(phone)){
            // Secondary member
            this.priceStrategy=new MemberPrice();
            this.integralStrategy=new CommonIntegral();
        }
        if ("333".equals(phone)){
            // Third-level member
            this.priceStrategy=new MemberPrice();
            this.integralStrategy=newDoubleIntegral(); }}public double doProcess(double price) {
        double processPrice = priceStrategy.processPrice(price);
        System.out.println("Payable :"+processPrice+"Yuan");
        System.out.println("Payment successful!");
        long integral = integralStrategy.processIntegral((long) price);
        System.out.println("User:"+phone+", increase the integral:"+integral);
        return 0; }}Copy the code

The membership class here can be upgraded by adding another method. For example, if the level 1 member pays 100 yuan for the first time, he/she will be upgraded to the level 2 member, and a policy object can be replaced.

conclusion

As you can see in my example above, I used some judgment in the constructor to create the membership class. It is easier to use the policy pattern with the factory pattern, encapsulating the process of creating the environment class into the factory class so that the responsibilities of the class are clear. If the strategy model is not applied, then we have to create a level 1 member, level 2 member and level 3 member, there will be duplication of the method code, and this is the case of a few classes, if a level 4 member, level 5… That class would be very bloated, and the code would have a lot of duplication.

Here is the difference between the policy pattern and the command pattern. The policy pattern focuses on reusing code to make up for the lack of inheritance. The command mode, which focuses on separating the user and the implementor of the method, can delay, undo the command, etc.

In the bridge pattern, the request is delegated to a specific implementation of an interface. In the bridge pattern, the request is delegated to a specific implementation of an interface. Instead of using an inherited implementation of N*M objects, the request is implemented using a composite object. The strategy pattern is to encapsulate the algorithm so that it can be replaced at any time.

— — — — — — — — — — — — — — —

The more you know, the more you don’t know.

If you have questions about this article, please comment directly or send me a personal message. If you think my writing is good, you can also support me by clicking “like”

Without permission, shall not be reproduced!