Design Pattern (1) Strategy Pattern

  • The summary of the design pattern combines high-quality articles on the Internet and an overview of the scenarios I used in my actual work.
  • I will summarize several design patterns that we often use as developers in our work.
  • Due to work reasons, the summary of the blog post is completed outside of work. Please correct me if there are any problems, thank you.
  • All the code about the design pattern will be hosted to: the design pattern code , welcome to pay attention.

Why do we use design patterns in daily work development? As a JAVA developer, the first thing I think of is "everything is an object". If you don't agree, I just want to say something new. But for the communication between developers, in order to be able to describe and solve the problem more accurately, design patterns have to be considered. What are the benefits? Of course, it is a matter of improving code reusability, scalability and reducing code redundancy. It can make the same developers better read and understand the code logic.

Six principles of design patterns

  • Open Close Principle

The principle of opening and closing means opening to expansion and closing to modification. When the program needs to be expanded, the original code cannot be modified to achieve a hot-swappable effect. So the summary is: for the program's scalability, easy maintenance and upgrade.

  • Liskov Substitution Principle

(From Baidu Encyclopedia) Liskov Substitution Principle is one of the basic principles of object-oriented design. The Richter Substitution Principle says that wherever a base class can appear, a subclass must appear. LSP is the cornerstone of inheritance and reuse. Only when the derived class can replace the base class and the function of the software unit is not affected, the base class can be reused, and the derived class can also add new behaviors to the base class. . The Richter substitution principle is a supplement to the "open-close" principle. The key step to realize the "open-close" principle is abstraction. The inheritance relationship between base class and subclass is the concrete realization of abstraction. Therefore, the Richter substitution principle is the specification of the concrete steps to achieve abstraction.

  • Dependence Lnversion Principle

This is the basis of the opening and closing principle. Specific content: For interface programming, rely on abstraction instead of concrete. (That is to say, the interface or abstract class does not depend on the implementation class, and the implementation class depends on the interface or abstract class. A more concise definition is: Object-Oriented Design (OOD)).

  • Interface Segregation Principle

Using multiple isolated interfaces is better than using a single interface. It is also a benchmark to reduce the degree of coupling between classes. All are for the service of "reducing dependence and reducing coupling".

  • Demeter Principle

(From Baidu Encyclopedia) Dimit's law is also called the Least Knowledge Principle (LKP). An entity should interact with other entities as little as possible to make the system functional modules relatively independent. That is to say, the less a class knows about other classes, the better. An object should know as little as possible about other objects, and only communicate with friends and not talk to strangers.

  • Composite Reuse Principle (Composite Reuse Principle)

The principle of composite reuse is to use composition/aggregation as much as possible instead of inheritance (indicating that when software reuse, it is necessary to use association relationships such as composition or aggregation as much as possible to achieve, and then consider using inheritance relationships to achieve).

Design pattern classification

Design patterns are generally divided into three categories

  1. Creation mode: prototype mode, singleton mode, factory method mode, abstract factory mode and builder mode.
  2. Structural mode: There are seven types of adapter mode, decoration mode, agent mode, appearance mode, bridge mode, combination mode and flyweight mode.
  3. Behavior mode: strategy mode, template method mode, observer mode, iteration sub mode, chain of responsibility mode, command mode, memo mode, status mode, visitor mode, intermediary mode, interpreter mode, eleven.

Let's start our strategy mode

Strategy mode

  • What is the strategy mode?
  1. In fact, the strategy model is the packaging of the algorithm, which separates the responsibility of the algorithm from the algorithm itself, delegates to different object management, and finally solves the problem of multiple if judgments. For example, let’s take a trip on a daily basis. Everyone may choose different modes of transportation, such as riding a bicycle, taking a train, taking a high-speed train, or taking an airplane. Although there are different ways to travel, the things you do are roughly the same-to travel.
  2. The above scenario can also be described like this: if there are many classes in a system, the difference between them is only in their behavior, then using the strategy mode can dynamically make an object choose a behavior in many behaviors (that is, the above Said to solve the problem of multiple if judgments).
  • scenes to be used
  1. I believe that many developers have been more or less exposed to erp system development. When conducting process audits, they can choose different types to achieve the final audit results. For example, there are review processes such as work report, KPI/OKR, and micro innovation.
  2. Let’s talk about our usual aggregate payment, such as Alipay, Xiaomi Pay, JD Pay, WeChat Pay, etc., large and small platforms. At this time, as developers, we have to dock so many platforms and write so many ifs. else if, think about it, it’s uncomfortable, or use the strategy pattern to solve the problem.
public String audit(String type){
    
    
	if(type.equals("工作汇报")) {
    
    
		//TODO
		return "工作汇报流程审核处理";
	}
	if(type.equals("KPI/OKR")) {
    
    
		//TODO
		return "KPI/OKR流程审核处理";
	}
	if(type.equals("微创新")) {
    
    
		//TODO
		return "微创新流程审核处理";
	}
	return "未找到审核处理流程";
}

Illustration of the strategy pattern from the network diagram:
Insert picture description here

  • Strategic mode environment construction
    Create a project named: springboot_design_pattern
  1. maven environment dependency
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
	
	 <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
	  <version>2.6</version>
    </dependency>

    <!--  配置文件显示-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.1</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>utf-8</encoding>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
          <version>2.2.5.RELEASE</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

Define an abstract role

package com.lee.strategy.service;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
public abstract class AuditService {
    
    

    /**
     * 抽象,子类具体实现
     * @param name
     * @param msg
     * @return
     */
    public abstract boolean operation(String name,String msg);

    /**
     * 公用方法
     * @param typeName
     */
    protected void updateAuditInfo(String typeName){
    
    
        System.out.println("更新了"+typeName+"审核信息");
    }
}

Concrete realization-micro innovation realization class

package com.lee.strategy.service.impl;

import com.lee.strategy.service.AuditService;
import org.springframework.stereotype.Service;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
@Service
public class InnovateAuditServiceImpl extends AuditService {
    
    
    @Override
    public boolean operation(String name, String msg) {
    
    

        //TODO
        System.out.println(name+"操作了微创新审核流程,留言内容:"+msg);

        //调用父类
        super.updateAuditInfo("微创新");
        return true;
    }
}

Specific implementation-KPI/OKR implementation class

package com.lee.strategy.service.impl;

import com.lee.strategy.service.AuditService;
import org.springframework.stereotype.Service;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
@Service
public class KPIAuditServiceImpl extends AuditService {
    
    
    @Override
    public boolean operation(String name, String msg) {
    
    

        //TODO
        System.out.println(name+"操作了KPI/OKR审核流程,留言内容:"+msg);

        //调用父类
        super.updateAuditInfo("KPI/OKR");
        return true;
    }
}

Specific implementation-work report implementation class

package com.lee.strategy.service.impl;

import com.lee.strategy.service.AuditService;
import org.springframework.stereotype.Service;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
@Service
public class WorkReportAuditServiceImpl extends AuditService {
    
    
    @Override
    public boolean operation(String name, String msg) {
    
    

        //TODO
        System.out.println(name+"操作了工作汇报审核流程,留言内容:"+msg);

        //调用父类
        super.updateAuditInfo("工作汇报");
        return true;
    }
}

Define an enumeration class to encapsulate the information corresponding to the three implementation classes, which is equivalent to the context. (Can be implemented in the database)

package com.lee.strategy.enumeration;

/**
 * @author zfl_a
 * @Desc 定义了枚举类实现,也可以定义在数据库中,根据类型取值
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
public enum AuditEnum {
    
    

    INNOVATE_ADUIT("2","innovateAuditServiceImpl"),
    KPI_AUDIT("3","KPIAuditServiceImpl"),
    WORK_REPORT_AUDIT("4","workReportAuditServiceImpl");

    private String type;
    private String impl;

    private AuditEnum(String type,String impl){
    
    
        this.type = type;
        this.impl = impl;
    }

    public static String getImpl(String type){
    
    
        for(AuditEnum auditEnum : AuditEnum.values()) {
    
    
            if(type.equals(auditEnum.getType())) {
    
    
                return auditEnum.getImpl();
            }
        }
        return null ;
    }

    public String getType() {
    
    
        return type;
    }

    public void setType(String type) {
    
    
        this.type = type;
    }

    public String getImpl() {
    
    
        return impl;
    }

    public void setImpl(String impl) {
    
    
        this.impl = impl;
    }
}

Define a specific business interface

package com.lee.strategy.service;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
public interface StrategyService {
    
    

    boolean audit(String name,String msg,String type);
}

Define a specific business interface implementation class

package com.lee.strategy.service.impl;

import com.lee.strategy.enumeration.AuditEnum;
import com.lee.strategy.service.AuditService;
import com.lee.strategy.service.StrategyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
@Service
public class StrategyServiceImpl implements StrategyService {
    
    

    //自动装配AuditService的所有实现类,以全类名首字母小写作为key
    @Autowired
    private Map<String, AuditService> auditMap ;

    @Override
    public boolean audit(String name, String msg, String type) {
    
    

        if(StringUtils.isBlank(type)) {
    
    
            return false ;
        }

        //根据不同类型审核
        String auditType = AuditEnum.getImpl(type);
        if(StringUtils.isNotBlank(auditType)) {
    
    
            AuditService auditService = auditMap.get(auditType);
            auditService.operation(name,msg);
        }

        return true;
    }
}

Define a strategy Controller

package com.lee.strategy.controller;

import com.lee.strategy.service.StrategyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zfl_a
 * @date 2020/8/10
 * @project springboot_design_pattern
 */
@RestController
@RequestMapping("/strategy")
public class StrategyController {
    
    

    @Autowired
    private StrategyService strategyService ;

    /**
     * 审核流程 返回值不建议Map,可定义成响应结果对象封装
     * @param name 审核人
     * @param msg 留言内容
     * @param type 类型 2微创新 3KPI/OKR 4工作汇报,在实际工作当中根据实际业务
     * @return
     */
    @PostMapping("/audit")
    public Map<String,Object> audit(String name,String msg ,String type) {
    
    

        Map<String,Object> results = new HashMap<>();
        results.put("code","200");
        results.put("msg","审核成功");

        if(StringUtils.isBlank(type)) {
    
    
            results.put("code","-1");
            results.put("msg","请传递审核类型");
            return results ;
        }

        boolean audit = strategyService.audit(name, msg, type);
        if(!audit) {
    
    
            results.put("code","-2");
            results.put("msg","审核失败");
        }
        return results ;
    }
}

Visit, as shown below:

Insert picture description here

Final result:

Insert picture description here

All the code about the design pattern will be hosted to: the design pattern code , welcome to pay attention. Hope to grow up with everyone!

Guess you like

Origin blog.csdn.net/qq_37640410/article/details/108544835
Recommended