“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

preface

XDM, it’s Singles’ Day today, is everyone cutting their hands off? It seems that this year, major e-commerce platforms do not offer strong discounts. In previous years, on November 11th, major e-commerce platforms would publish the latest transaction data of their platforms in real time. This year, xiaobian has not found the latest data information of the transaction amount of Singles’ Day on relevant platforms on the Internet. The latest figures are not released this year. There may be surprises when the sales figures of singles’ Day are announced on various platforms after the end of the day.

I believe that those who have done e-commerce know that different customers may place orders for the same goods, but under different trading methods, there will be different total price information of goods. We all adopt if… Else to judge the trade method and price calculation algorithm, or use design mode? In view of this situation, the strategic design mode is adopted to design.

The strategy pattern

Strategy pattern refers to the relatively stable strategy name with certain action content. This design pattern belongs to behavior pattern. The strategy mode mainly solves the problem of using if… Else is complicated and difficult to maintain. Using policy mode, different algorithms and businesses can be encapsulated independently, and different algorithms and logic can be dynamically invoked independently during the project running.

Advantages:

  • Good scalability and maintenance
  • Avoid using multiple conditional judgments and reduce if… else
  • You can freely switch between different business logic dynamically

disadvantages

  • There will be many implemented policy classes
  • Policy classes need to be exposed

Case to understand

Some time ago, when developing the trading domain platform, there was a need to calculate the total price information of the goods ordered according to different trading methods. The following example is used for analysis. First of all, we know that there are N ways of trade. Four of them are listed in the example, namely, way A, way B, way C and way D.

  • Trade method A. This kind of trade method generally refers to the way of self-payment by users, so there is no express delivery fee, customs duty and other expenses. The total price calculation logic used is :(unit price * quantity) – minus discount.
  • Trade method B refers to the general express mail, express freight, no other costs. The total price of goods in this way of trade is calculated as :(unit price * quantity of goods) – total amount of preferential price + express delivery cost.
  • Trade mode C, which needs to be imported from abroad, may have two express fees, one is overseas express freight, the other is domestic express fees. In imported goods, customs clearance is required, resulting in tariff costs. Therefore, the total price of the goods is calculated as :(unit price * quantity) – preferential amount + the first section of express delivery fee + the second section of express delivery fee
  • Trade mode D, which needs to be imported from abroad, may have two express costs, one is overseas express freight, and the other is domestic express cost. In imported goods, customs clearance is required, resulting in tariff costs. Therefore, the total price of the goods is calculated as :(unit price * quantity) – preferential amount + the first section of express delivery fee + the second section of express delivery fee.

Basic commodity information

Basic commodity information includes commodity code, commodity unit price, commodity quantity, preferential amount, tax amount, freight amount in the first paragraph and freight amount in the second paragraph, which are the basic business parameters for the calculation of total commodity price. This paper will calculate the price based on these parameters.

@Data
@ApiModel("Commodity Information")
public class Goods {

    private String skuCode;

    private BigDecimal price;

    private int num;

    private BigDecimal discount;

    private BigDecimal taxes;

    private BigDecimal firstFreight;

    private BigDecimal secondFreight;

}
Copy the code

Policy interface

Define a policy interface that all policies implement.

public interface TradeTypeStrategy {

    BigDecimal getGoodsTotalPrice(Goods goods);
}

Copy the code

Trade type object

Define an object of trade type and maintain a reference to a policy interface object.

public class TradeType {

    private TradeTypeStrategy tradeTypeStrategy;

    public TradeType(TradeTypeStrategy tradeTypeStrategy){
        this.tradeTypeStrategy = tradeTypeStrategy;
    }

    public BigDecimal executeStrategy(Goods goods){
        returntradeTypeStrategy.getGoodsTotalPrice(goods); }}Copy the code

Write the implementation

According to the actual needs of business, write a variety of implementation classes, implementation classes for business logic and algorithm development. Execute different policies and invoke different business logic and algorithms. The example implements trade mode A, B, C and D, and the simple codes are as follows:

Method of trade A total price calculation logic is :(commodity unit price * quantity) – minus preferential treatment.

public class TradeTypeStrategyA implements TradeTypeStrategy {

    /** ** ** /
    @Override
    public BigDecimal getGoodsTotalPrice(Goods goods) {
        BigDecimal goodsTotalPrice = goods.getPrice().multiply(BigDecimal.valueOf(goods.getNum())).subtract(goods.getDiscount());
        returngoodsTotalPrice; }}Copy the code

B: the total price shall be calculated as :(unit price * quantity of goods) – total amount of discount + express delivery fee

public class TradeTypeStrategyB implements TradeTypeStrategy {

    @Override
    public BigDecimal getGoodsTotalPrice(Goods goods) {
        BigDecimal goodsTotalPrice = goods.getPrice().multiply(BigDecimal.valueOf(goods.getNum()))
                .subtract(goods.getDiscount()).add(goods.getFirstFreight());
        return goodsTotalPrice;
    }
Copy the code

The total price of trade method C is :(unit price of commodity * quantity) – preferential amount + the first section of express delivery fee + the second section of express delivery fee

public class TradeTypeStrategyC implements TradeTypeStrategy {
   
    @Override
    public BigDecimal getGoodsTotalPrice(Goods goods) {
        BigDecimal goodsTotalPrice = goods.getPrice().multiply(BigDecimal.valueOf(goods.getNum()))
                .subtract(goods.getDiscount()).add(goods.getFirstFreight()).add(goods.getTaxes());
        returngoodsTotalPrice; }}Copy the code

The total price of trade mode D is :(unit price of commodity * quantity) – preferential amount + the first section of express delivery fee + the second section of express delivery fee

public class TradeTypeStrategyD implements TradeTypeStrategy {

    @Override
    public BigDecimal getGoodsTotalPrice(Goods goods) {
        BigDecimal goodsTotalPrice = goods.getPrice().multiply(BigDecimal.valueOf(goods.getNum()))
                .subtract(goods.getDiscount()).add(goods.getFirstFreight()).add(goods.getSecondFreight()).add(goods.getTaxes());
        returngoodsTotalPrice; }}Copy the code

Run the test

Write the test class, this test uses the same commodity information, when the user places an order under different trade methods, you can see that the total price of the output order goods is different.

public class MainTrade {
    public static void main(String[] args) {
        Goods goods = new Goods();
        goods.setSkuCode("G888888");
        goods.setPrice(BigDecimal.valueOf(100));
        goods.setFirstFreight(BigDecimal.valueOf(20));
        goods.setNum(3);
        goods.setSecondFreight(BigDecimal.valueOf(8));
        goods.setDiscount(BigDecimal.TEN);
        goods.setTaxes(BigDecimal.valueOf(32));
        TradeType tradeTypeA = new TradeType(new TradeTypeStrategyA());
        System.out.println("The total price of trade mode A is =" + tradeTypeA.executeStrategy(goods));
        TradeType tradeTypeB = new TradeType(new TradeTypeStrategyB());
        System.out.println("The total price of mode B is =" + tradeTypeB.executeStrategy(goods));
        TradeType tradeTypeC = new TradeType(new TradeTypeStrategyC());
        System.out.println("The total price of trade mode C is =" + tradeTypeC.executeStrategy(goods));
        TradeType tradeTypeD = new TradeType(new TradeTypeStrategyD());
        System.out.println("The total price of trade mode D is ="+ tradeTypeD.executeStrategy(goods)); }}Copy the code

As shown in the figure below, under different trade modes, the total price of output orders is different. The sample information is for reference only, there is more complex business logic and in calculating the total price information

conclusion

Well, the above is the introduction to the use of strategy mode, thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.