Summary of design patterns (practice 1)

Time:2021-9-18

Practice leads to truth

The knowledge content related to the two design patterns summarized above has a relatively clear understanding of how to standardize the code and write the code. In writing the code, we will also deliberately write how the code should be written, rather than writing the code function logic into a pile like noodles.

demand

The following is the code I modified according to a new requirement I received recently. The demand is to modify and expand more activity types under the original activity. The original demand has only fixed activities (such as buy one get one free, buy two get one free, and the second item enjoys a discount). If you want to set buy one get two free, you can’t realize it. For this, you need to greatly change the original activity and divide the activity into five types (meet the full reduction of activities, meet the activity discount, buy x pieces, get x pieces free, buy it now activities, and enjoy the x-th activity). In this way, the operation can meet whatever activities it wants to configure when configuring activities.

requirement analysis

Only the general idea and pseudo code are written here.

For each activity type, you need to check whether the activity type is legal, whether it meets the use conditions and preferential price of the activity, and can be extracted as a public part. For this, I created an active interface class.

//Active interface class

Because there are five different types, five different activity classes are created here to inherit the interface and implement the methods of the interface respectively.

//Full minus type activity class

After the five activity classes are created here, the code coupling and readability will be poor if the calling of different activity classes is written in a procedural way. For this, I created an activityfactoryservice activity factory service class. Call and access control of different activity classes are implemented on this class. The following is the relevant code of the activity factory service class. If you need to add other activity types later, you only need to add an activity class and add a new if branch in the getactivityfactory method. Of course, there should not be too many activity types, so I use ifelse to judge here.

class ActivityFactoryService implements ActivityInterface

The above is my process of analyzing a new requirement and processing the implementation code.

This work adoptsCC agreement, reprint must indicate the author and the link to this article