“This is the fifth day of my participation in the Gwen Challenge.

strategy

Strategy refers to multiple approaches to one thing in life, for example, I want to go to Beijing, usually by train, high-speed rail, carpooling, etc., or self-driving. One goal can be realized in multiple ways, and there may be many branches in the business, how to instantiate these branches and refuse if.. Else, this time with dry goods ha ha 😄

Recently updated article type are more diverse, is actually want to broaden their knowledge system, as a design pattern, we also as project developers considering product will need to think of iterative process, such as mode of payment now, you open a stationery shop, pay the scene is divided into cash, bank CARDS, and sweep code, and code can be divided into WeChat, pay treasure, Unionpay and other payment methods, now there are such as emerging coupon full reduction, activities, and free lottery, etc., these need dynamic record payment methods, one by one, this payment business tree is more and more rich, do we always if/else go on?

No, we can’t;

The strategy pattern

Strategy, that is, strategy, in order to achieve a certain scene, abstract out a variety of implementation methods, the control and implementation of these methods is the strategy mode we are going to talk about today.

There may be no specific scene, it is difficult to understand, such as your own identity, in the face of different people, your identity will change, the address will change;

For example, in the face of my grandpa, I will say hello grandpa, how is the body. Hello to my mom, mom, how are you at home recently…

For different objects, the results are different;

This time we are going to start customizing the scene, and let’s go;

Scene:

When you buy something on JINGdong, you can generally get the product discount, which can be divided into various types, including full reduction (200 minus 20), direct reduction, discount coupon (8.8), N yuan purchase, among which, the discount type can be used as a variety of ways to realize the discount.

I have just graduated from school.

public class CouponDiscountService {



    public double discountAmount(int type, double typeContent, double skuPrice, double typeExt) {

// 1

        if(1 = =type) {

            return skuPrice - typeContent;

        }

// 2

        if(= = 2type) {

            if (skuPrice < typeExt) return skuPrice;

            return skuPrice - typeContent;

        }

// 3. Discount coupons

        if(3 = =type) {

            return skuPrice * typeContent;

        }

// 4

        if(4 = =type) {

            return typeContent;

        }

        return 0D;

    }



}

Copy the code

This method is our common matching method, used to do a small range of matching, specify enumeration values to classify, and then implement separately, but this code will greatly reduce the coupling, maintainability, and readability.

How does strategic mode teach you to play

Customize the specific preferences, and then implement the implementation class, which is the implementation of various policies, where we use generic methods as input parameter representations for the common interface;

public interface ICouponDiscount<T> {



/ * *

* Calculation of coupon amount

* @param couponInfo coupon discount information; Direct reduction, full reduction, discount, N yuan purchase

* @param skuPrice SKu amount

     * @returnAmount after concession

* /

    BigDecimal discountAmount(T couponInfo, BigDecimal skuPrice);



}

Copy the code

Customized interface, divided into standard discount type T, and the original price of the product, return the price of the product after the discount,

Preferential type implementation

Full reduction

Usually said to be full, when the amount is full, subtract and add, if it does not meet the original price, (200 minus 20)

public class MJCouponDiscount implements ICouponDiscount<Map<String,String>>  {



/ * *

* Full subtraction calculation

* 1. Determine -n elements after x elements are satisfied, otherwise, no reduction is made

* 2. The minimum payment amount is 1 YUAN

* /

    public BigDecimal discountAmount(Map<String,String> couponInfo, BigDecimal skuPrice) {

    

    

// The current set price is 200 minus 20

        String x = couponInfo.get("x");

        String o = couponInfo.get("o");



// If the value of the item is less than the value of the item, return the original price of the item directly

        if (skuPrice.compareTo(new BigDecimal(x)) < 0) return skuPrice;

// Subtract discount amount judgment

        BigDecimal discountAmount = skuPrice.subtract(new BigDecimal(o));

        if (discountAmount.compareTo(BigDecimal.ZERO) < 1) return BigDecimal.ONE;



        return discountAmount;

    }

}

Copy the code

For those of you who are not familiar with the compareTo interface, here is a simple demo

public class Test {

 

    public static void main(String args[]) {

        String str1 = "Strings";

        String str2 = "Strings";

        String str3 = "Strings123";

 

        int result = str1.compareTo( str2 );

        System.out.println(result);

/ / 0

        result = str2.compareTo( str3 );

        System.out.println(result);

/ / 3

        result = str3.compareTo( str1 );

        System.out.println(result);

/ / 3

    }

}

Copy the code

CompareTo is mainly used to compare objects,

  • If the argument string is equal to this string, the value 0 is returned;
  • If the string is less than the string argument, a value less than 0 is returned;
  • If the string is greater than the string argument, a value greater than 0 is returned.

lapse

ublic class ZJCouponDiscount implements ICouponDiscount<Double>  {



/ * *

* Direct subtraction

* 1. Use the price of the product minus the preferential price

* 2. The minimum payment amount is 1 YUAN

* /

    public BigDecimal discountAmount(Double couponInfo, BigDecimal skuPrice) {

        BigDecimal discountAmount = skuPrice.subtract(new BigDecimal(couponInfo));

        if (discountAmount.compareTo(BigDecimal.ZERO) < 1) return BigDecimal.ONE;

        return discountAmount;

    }



}

Copy the code

# # # # with discount coupons

public class ZKCouponDiscount implements ICouponDiscount<Double> {





/ * *

* Discount calculation

* 1. The final amount to be paid is the product price multiplied by the discount ratio

* 2. Keep two decimal places

* 3. The minimum payment amount is 1 YUAN

* /

    public BigDecimal discountAmount(Double couponInfo, BigDecimal skuPrice) {

        BigDecimal discountAmount = skuPrice.multiply(new BigDecimal(couponInfo)).setScale(2, BigDecimal.ROUND_HALF_UP);

        if (discountAmount.compareTo(BigDecimal.ZERO) < 1) return BigDecimal.ONE;

        return discountAmount;

    }



}

Copy the code

N yuan to buy

public class NYGCouponDiscount implements ICouponDiscount<Double> {



/ * *

* N yuan purchase purchase

* 1. Buy a fixed amount no matter how much the original price is

* /

    public BigDecimal discountAmount(Double couponInfo, BigDecimal skuPrice) {

        return new BigDecimal(couponInfo);

    }



}

Copy the code

conclusion

For the strategy mode, mainly according to a variety of implementation methods abstract the standard interface, the use of interface and implementation class relations, a variety of implementation, no longer rely on the simple if… Else single value matching, complete the task. The code on the top is from my new product, “Relearning Java Design Pattern” by Fugel. I feel that the type of this coupon is more vivid, and in fact, it is just to let you understand the strategy pattern. It could be a factory-plus-proxy plus policy pattern scenario to implement AOP facets,

All technologies need the support of actual business to give full play to their value, so they should consider specific scenarios to achieve, well, that’s all for today’s sharing.

I’m Luca. I’m going to go to bed early. I was up late last night and my body was a little bit stressed.