There are too many if-else statements in the company system. I eliminated if-else with design patterns

I used enumeration to eliminate the if-else statement in the previous article. If you are interested, you can read this article of mine:

How to use enumeration to eliminate if/else?-Enumeration advanced usage

This time I used other methods to eliminate if-else.

background

You must use if-else statements in your usual development. However, a large number of if-else statements are not conducive to code reading and affect code complexity. Anyway, I had a headache while removing Sonar's odor.

There were too many if-else problems in the code of the previous company system, which caused the code to be inelegant. To explain here, I simplify the business logic.

Suppose I have a method to calculate the actual price, which requires input of the user's level and the actual price of the product, and returns the true price of the product, the code is as follows:

Here levelis the level of the user, which originalPriceis the original price of the product. If the user level is "normal", the real price returned is the original price multiplied by 1.0. If the user level is "vip", the real price returned is the original price multiplied by 0.9. Otherwise, the original price is returned.

As a result, the price of "vip" is:

getActualPrice()测试的真实价格为:90.0

The above code may look fine, but the user's level may also have super vip (svip), and may also have ssvip. There may be more, then this method if-else will be very many. And will often modify this method, which violates the opening and closing principle in the design principle. For this reason, I wonder if I can achieve levellevel expansion without modifying this method .

Use design patterns to eliminate if-else

After much deliberation, I decided to use design patterns to eliminate if-else.

CalculateStrategy

public interface CalculateStrategy {
    String userLevel();
    BigDecimal discount(BigDecimal originalPrice);
}

Here first write a calculation interface, which defines two methods: obtaining user level, and the corresponding price calculation method.

NormalStrategy

@Component
public class NormalStrategy implements CalculateStrategy {
    @Override
    public String userLevel() {
        return "normal";
    }

    @Override
    public BigDecimal discount(BigDecimal originalPrice) {
        return originalPrice.multiply(new BigDecimal("1.0"));
    }
}

Implementation class of normal level.

@Component
public class VipStrategy implements CalculateStrategy {
    @Override
    public String userLevel() {
        return "vip";
    }

    @Override
    public BigDecimal discount(BigDecimal originalPrice) {
        return originalPrice.multiply(new BigDecimal("0.9"));
    }
}

Implementation class at the vip level.

Our code to calculate the real price is as follows:

Here I created a map. The key of the map stores the user level leveland the value stores CalculateStrategythe object. When the system is started, the IoC container will SaleServicecreate objects, and then the map will be stored in all implemented CalculateStrategyobjects.

Then write a getActualPriceWithStrategy()method to calculate the actual price of the product based on the user level. If the user increases the level, only you need to add the appropriate class, such as: SvipStrategy, SSvipStrategyand the like. In this way, there is no need to modify getActualPriceWithStrategy()the content, and the safety of this method is guaranteed.

The test code is as follows:

Test Results:

getActualPriceWithStrategy()测试的真实价格为:90.0

In fact, I have used the strategy pattern in the design pattern above. I extracted the algorithm in if-else and encapsulated it separately in a class, so that the algorithm is independent of the caller. If you change the algorithm, you only need to change the algorithm class, without changing Caller.

Of course, if-else cannot be eliminated just by using the strategy mode, you can think about it:

Are there any other design patterns used in the above code?

Recommended in the past

Scan the QR code to get more exciting. Or search Lvshen_9 on WeChat , you can reply to get information in the background

1.回复"java" 获取java电子书;

2.回复"python"获取python电子书;

3.回复"算法"获取算法电子书;

4.回复"大数据"获取大数据电子书;

5.回复"spring"获取SpringBoot的学习视频。

6.回复"面试"获取一线大厂面试资料

7.回复"进阶之路"获取Java进阶之路的思维导图

8.回复"手册"获取阿里巴巴Java开发手册(嵩山终极版)

9.回复"总结"获取Java后端面试经验总结PDF版

10.回复"Redis"获取Redis命令手册,和Redis专项面试习题(PDF)

11.回复"并发导图"获取Java并发编程思维导图(xmind终极版)

Another: Click [ My Benefits ] to have more surprises.

 

Guess you like

Origin blog.csdn.net/wujialv/article/details/109109402