Big brother beep beep

Both life and code face many choices. Code is filled with countless if/else. Isn’t life the same? With countless forks in the road, we cannot avoid these choices, but we can make them more elegantly — design patterns.

Trouble in A Relationship

Unfortunately, today to the bonus time, the girlfriend for the first time to urge debt.


Turn sadness into motivation

Every time my wallet was empty, I was even more stimulated to write code. I found that TYrannosaurus Rex had used 3 Ifs in one breath this time. But if I had paid more, I would have had to say a dozen ifs. No, I have to teach her about design patterns, educate her, teach her how to kill if/else in code.

If the pseudo code

public String getBonusPlan(Integer bonus) {

    if (bonus.equals(100)) {

        if(Hungry) {

            return "Eat Xiabu Hot pot";

        }

        return "Thinking about it.";

    } else if (bonus.equals(300)) {

        if(Hungry) {

            return "Eat Shu Warrior Hot Pot";

        }

        return "Thinking about it.";

    } else if (bonus.equals(500)) {

        return "Eat Haidilao Hotpot";

    }

    // A large wave of hot pot attack...

}

Copy the code

Factory mode + Policy mode

This is not a standard factory pattern or a standard policy pattern, but a combination of the two as required by the business. This pattern is used a lot at work, and if you’re interested, we can write a separate article about factory and strategic design patterns.

Enter strategy mode

  • Start by defining a general interface class
// Bonus interface

public interface BonusService {

   // How to use the bonus

   public String useBonusPlan (Integer bonus);

}

Copy the code
  • Bonus use: go to Xiabu to eat hot pot
public class XiabuBonusService implements BonusService {

    @Override

    public String useBonusPlan(Integer bonus) {

        if(Hungry) {

            return "Go suck food." + bonus + "Yuan's Hot pot";

        }

        return "Thinking about it.";

    }

}

Copy the code
  • Bonus use way one: go to Shu warrior to eat hot pot
public class ShudaxiaBonusService implements BonusService {



    @Override

    public String useBonusPlan(Integer bonus) {

        if(Hungry) {

            return "Go to Shu Warrior to eat." + bonus + "Yuan's Hot pot";

        }

        return "Thinking about it.";

    }

}

Copy the code
  • Bonus usage: go to haidilao to eat hot pot
public class HaidilaoBonusService implements BonusService {



    @Override

    public String useBonusPlan(Integer bonus) {

        return "Go fishing at the bottom of the sea." + bonus + "Yuan's Hot pot";

    }

}

Copy the code

Changes after using the policy mode

public String getBonusPlan(Integer bonus) {

    

    if (bonus.equals(100)) {

        XiabuBonusService xiabuBonusService = spring.getBean(XiabuBonusService.class);

        return xiabuBonusService.useBonusPlan(bonus);

    } else if (bonus.equals(300)) {

        ShudaxiaBonusService shudaxiaService = spring.getBean(ShudaxiaBonusService.class);

        return shudaxiaService.useBonusPlan(bonus);

    } else if (bonus.equals(500)) {

        HaidilaoBonusService haidilaoBonusService = spring.getBean(HaidilaoBonusService.class);

        return haidilaoBonusService.useBonusPlan(bonus);

    }

}

Copy the code

As you can see, the getBonusPlan method is much more readable. We have encapsulated the eating hotpot algorithm in a policy class, but there is no reduction in the if determination of which algorithm to use in which situations. Keep optimizing the code!

Simple factory design patterns

// Create a bonus factory class

public class BonusStrategyFactory {



    // Use map to save the policy class on how to use bonuses

    private static Map<Integer, BonusService> strategyMap

    = new ConcurrentHashMap<Integer, BonusService>();



    // Find the corresponding usage policy by the amount of bonus

    public  static BonusService getByBonus(Integer bonus){

        return strategyMap.get(bonus);

    }



    // Register the bonus and the corresponding usage policy in the map

    public static void register(Integer bonus, BonusService bonusService){

        Assert.notNull(bonus,"bonus can't be null");

        strategyMap.put(bonus, bonusService);

    }

}

Copy the code

Code changes after adding factory design patterns

public String getBonusPlan(Integer bonus) {

    // Get the corresponding usage strategy class through the bonus in the factory

    BonusService strategyService = BonusStrategyFactory.getByBonus(bonus);

    // Call the corresponding method of the policy class

    return strategyService.getBonusPlan(bonus);

}

Copy the code

As you can see, the policy design pattern + factory design pattern makes our code very simple. The only drawback is that there are some more policy classes, but it is very decoupled. The above code is just pseudo code. In real, complex business scenarios, design patterns can play a very important role.

Register policies with the Map

We use the Spring InitializingBean interface to achieve, take the Shu Warrior class for example.

public class ShudaxiaBonusService implements BonusService.InitializingBean {



    @Override

    public String useBonusPlan(Integer bonus) {

        if(Hungry) {

            return "Go to Shu Warrior to eat." + bonus + "Yuan's Hot pot";

        }

        return "Thinking about it.";

    }



    @Override

    public void afterPropertiesSet(a) throws Exception {

        // Register to Map

        BonusStrategyFactory.register(300.this);

    }

}

Copy the code

Brother epilogue

Although the private money ZA can’t hide, but through this painful lesson, learn a new technology, very good, let the storm come more violent.

Follow wechat public account: IT elder brother

Java actual combat project video tutorial: you can get 200G, 27 sets of actual combat project video tutorial

Reply: Java learning route, you can get the latest and most complete a learning roadmap

Re: Java ebooks, get 13 must-read books for top programmers

Java foundation, Java Web, JavaEE all tutorials, including Spring Boot, etc

Reply: Resume template, you can get 100 beautiful resumes