How to use the strategy pattern in Java to reduce the use of if / else branches

Table of contents

1. Strategy mode

1.1, the strategy pattern contains three roles:

2. Demand

2.1, traditional way

2.2, strategy pattern implementation

2.2.1, create a new PolicyPatternController.java

2.2.2, Express.java (entity class)

2.2.3. Define an interface: PolicyPatternService.java

2.2.4. Define 3 implementation classes to implement the PolicyPatternService interface


1. Strategy mode

        The Strategy pattern is a design pattern that allows dynamic selection of an algorithm's behavior at runtime. It defines a series of algorithms and encapsulates each algorithm into an independent class, and these algorithms can be used interchangeably. In the strategy pattern, the behavior or algorithm of a class can be changed at runtime without modifying its structure.

1.1, the strategy pattern contains three roles:

  1. Context (context): Holds a reference to a strategy object and calls the algorithm provided by the strategy object.

  2. Strategy (Strategy): Defines the public interface of all supported algorithms and provides specific implementations.

  3. ConcreteStrategy (concrete strategy): implement the Strategy interface and provide specific algorithm implementation.

      Strategy mode can help us avoid a large number of if-else statements or switch statements, making the code more concise, easy to maintain and expand. It is widely used in scenarios that need to dynamically switch algorithms, such as sorting, searching and other algorithms.

2. Demand

     Different processing is performed according to different types of incoming

2.1, traditional way

@Service
public class TesiImpl implements PolicyPatternService {

  

   @Override
   public String sayHello(String type) {
      if ("1".equals(type)) {
         // TODO 具体业务代码
      }
      if ("2".equals(type)) {
         // TODO 具体业务代码
      }
      if ("3".equals(type)) {
         // TODO 具体业务代码
      }
      if ("4".equals(type)) {
         // TODO 具体业务代码
      }
      .................................

      return null;
   }
}

This way of writing is poor in readability, and it is not easy to maintain the project later. . . . . .

2.2, strategy pattern implementation

2.2.1, create a new PolicyPatternController.java

@RestController
@RequestMapping("celue")
@Slf4j
public class PolicyPatternController {

    @Autowired
    private List<PolicyPatternService> policyPatternService;

    @PostMapping("test")
    public Result test(@RequestBody Express expres) {
        PolicyPatternService service = policyPatternService.
                stream().
                filter(l -> l.isCeLueModel(expres.getType())).findFirst().orElse(null);
        String name = service.sayHello();
        return Result.ok(name);
    }
}

2.2.2, Express.java (entity class)

@Data
public class Express {

   @ApiModelProperty("根据不同的类型实现不同的方法")
   private String type;

}

2.2.3. Define an interface: PolicyPatternService.java


public interface PolicyPatternService {

    //判断传入的类型
    Boolean isCeLueModel(String type);
    
    // 方法
    String sayHello();
}

2.2.4. Define 3 implementation classes to implement the PolicyPatternService interface

1. JDServcieImpl.java

@Service
public class JDServcieImpl implements PolicyPatternService {
    
    //判断传入的类型
    @Override
    public Boolean isCeLueModel(String type) {
        return Objects.equals(type, "1");
    }

    @Override
    public String sayHello() {
        // TODO 具体业务代码
        return "我是京东";
    }
}

2. YZServcieImpl.java

@Service
public class YZServcieImpl implements PolicyPatternService {

   //传入的类型
   @Override
   public Boolean isCeLueModel(String type) {
      return Objects.equals(type, "2");
   }

   @Override
   public String sayHello() {
      // TODO 具体业务代码
      return "我是邮政";
   }
}

3. ZTServcieImpl.java

@Service
public class ZTServcieImpl implements PolicyPatternService {
 
   //判断传入的类型
   @Override
   public Boolean isCeLueModel(String type) {
      return Objects.equals(type, "3");
   }

   @Override
   public String sayHello() {
      // TODO 具体业务代码
      return "我是中通";
   }
}

4. Test effect type = 1

5. Test effect type = 2

6. Test effect type = 3

Guess you like

Origin blog.csdn.net/XikYu/article/details/130877675