preface

Recently, I received a small demand in the company to expand the existing application rules for trial users. Our scenario looks something like this:

Java core learning notes + interview actual practice sharing!

According to the above conditions, we can come to the conclusion that:

  • Our main process is mainly based on and or OR relationship.
  • If there is a mismatch, in fact, our subsequent process does not need to be executed, it is necessary to have a short-circuit function.
  • For the current situation, if I change on the original basis, as long as I pay a little attention to solve the problem that the demand is not very big, but the maintainability is very poor.

After some consideration, I decided to refactor this part.

Rule executor

In view of this requirement, I first sorted out the general design of our rule executor, and then I designed a V1 version to share with you. If you also have such a case, you can share messages with me. The following part is mainly about the design and implementation process and code.

Design of rule executor

Abstract and implement rules

Actuator construction

The invocation of the executor

conclusion

Advantages and disadvantages of a rule executor

Advantages:

  • Relatively simple, each rule can be independent, rules, data, executor split out, the caller is more orderly;
  • I defined the convert method in the Rule template class to convert parameters so that I could extend the scenario data required for a particular Rule.

Disadvantages:

  • The upper and lower rules have data dependencies. If it is not reasonable to directly modify the DTO of the common transport object, it is recommended to build data in advance.