scenario

Daily development, if-else statement to write a lot of it? When there are too many branches of logic, if-else layer after if-else layer, although the business function is implemented, but it is really not elegant, especially for the obsessive-compulsive ape like me, see so many if-else, my head is always thinking of unlocking a new position: kill too many if-else!!

This article will introduce three plate axe means:

  • Priority to judge the conditions, conditions do not meet, the logic timely interrupt return;
  • Integration strategy mode;
  • Strategy mode + factory + singleton mode, icing on the cake;

Next, I will attach a business code I wrote a long time ago. The core logic is to grant users corresponding rights (days of VIP video membership + number of lucky draw opportunities) according to the price package purchased by users in the payment callback.

Oh my God, too many if-else… (If you can’t see clearly, click on the picture to enlarge it) 1. The priority judgment condition is not met

This is very easy to understand, which means that in business logic, we should filter out the unqualified ones first, instead of nesting layer upon layer of if-else judgment. Let’s look at the code diagram: 2. Transformation of strategy mode

Firstly, replace the logic mentioned at the beginning of the article with the strategy mode. After recharging, users can increase the number of VIP days and the number of sampling inspection opportunities for users according to the price package (how much money they pay). Here, I simplify it into the action of “adding different VIP days for sports member videos to users according to the price package” : On the face of it, the code looks a little more elegant, but it doesn’t completely break up with the if-else recharge method, and the recharge() method can be set up separately by instantiating a different strategy with priceCode: 3. Policy mode + factory + singleton mode, icing on the cake

Next use “factory class + singleton” to spice up the code: Source: love1024.blog.csdn.net/article/details/104955363