Java uses policy patterns to optimize too much if else code
preface
Not surprisingly, this should be the last time I shared it years ago. This time, I'll give you some tips that will be used in actual development.
For example, do you usually write code like this:
if(a){ //dosomething }else if(b){ //doshomething }else if(c){ //doshomething } else{ ////doshomething }
It's good to have fewer conditions. Once there are too many else if, the logic here will be chaotic and easy to make mistakes.
For example:
Judgment conditions of a client command extracted from CIM.
At the beginning, there were few conditions, so there was not so much direct writing; Now there are many functions, so I have to check carefully every time an else condition is added, for fear of affecting the previous logic.
This time, he was finally rebuilt when he couldn't bear it. After reconstruction, the structure here is as follows:
Finally, it is directly changed into two lines of code, which is much simpler.
All previous implementation logic is extracted into other implementation classes separately.
In this way, whenever I need to add an else logic, I only need to add a class to implement the same interface. Each processing logic is independent of each other and does not interfere with each other.
realization
A sketch is drawn according to the current implementation.
The overall idea is as follows: