The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
设计模式:从聚合支付业务的设计来聊聊策略模式

1. preface

Mobile payment is now very popular in China. Even the seventies-year-old lady at the breakfast stall downstairs uses Alipay and Weixin Pay to sell egg cakes. If you are asked to make an App, you must definitely consider multiple payment channels to ensure that you can get customers. What would you design if you were given access to multiple payment channels?

2. common writing

Generally, the following writing is easy to create:

      (){

        =;
         (){
            
        }  (){
            
        }  (){
           
        }
        ;
    }

If four or five payments are integrated, the code will not be able to read at least a few thousand lines, and changing the logic of one payment can easily change the logic of other payments. Therefore, reasonable design is needed to avoid this risk.

3. strategy pattern

Most payments can be simplified to this process:

the middlePre-payment logicandPost-payment processing logicIt is the customized business logic of the client. Requests sent to the payment server will only carry parameters corresponding to the specific requirements of the payment server to invoke different payments.SDK。So we establish policies corresponding to payment methods to isolate and distinguish them and reduce their coupling. When preparing to pay, we only need to choose the corresponding strategy.

This uses the strategy pattern in the design pattern:

Combined with the above class diagram, let's talk about the main roles in the strategy model based on requirements.

  • StrategyInterface. This interface is used to declare independent execution strategies for each method and to encapsulate the unique algorithm logic of specific policies.
  • ConcreteStrategyisStrategyimplementation class. Algorithm logic for different strategies is implemented. Such as the call details of each payment, etc.
  • ContextContext. It references specific policies through the policy interface and uses specific policies to execute logic. At the same time, the commonalities of all policies can also be handled uniformly in this class. In aggregating payment requirements, we pass in a strategy, first implement the pre-payment logic, then use the strategy, and after the strategy is executed, we implement the post-common logic.
  • ClientClient. Create a policy object and pass it to the contextContext, and then the specific policy is run by the context.

The combined business logic looks like this:The request reaches the client, and the client builds a corresponding policy object based on the payment channel contained in the request and hands it over to the context object to perform the payment process.

Then we can construct three policy objects for Alipay, Weixin Pay, and UnionPay Payment respectively AliPayStrategyWechatPayStrategyUnionPayStrategy Let's simulate the execution strategy:

   {

       ([]) {
        
        = ;
        = ;
        = ;

         (..().()) {
            =  ();
            =  ();
        }
         (..().()) {
            =  ();
            =  ();
        }

         (..().()) {
            =  ();
            =  ();
        }

         (.()) {
            =  ();.();.();
        }
    }
}

We get the payment ID in the request, then initialize the corresponding payment policy, encapsulate the specified request parameters, and hand them to the context objectPayContext to execute the request. If you add anything moreApplePayor something like that to achieve.ApplePayStrategyJust do it.

4. advantages and disadvantages

Not all strategic models have positive effects.

4.1 advantages

  • We isolate the implementation of the algorithm from the use of the algorithm. The implementation of the algorithm only cares about the logic of the algorithm, and the use of the algorithm only cares about what algorithm to use under what conditions.
  • The open-close principle requires no modification of the context object. If you want to expand, you only need to introduce new strategies.
  • Dynamic de-switching algorithm based on conditions at runtime.
  • While adapting to individuality, you can also accommodate commonalities.

4.2 disadvantages

  • The client must clearly know the conditions of the activation policy.
  • Introduce too many policy classes.
  • Can be replaced by some functional interfaces. pseudocodePay.request(data).strategy(data->{ })

5. summary

Policy patterns are also common and widely used design patterns. Today, we learned the strategy model from aggregated payments and also conducted an analysis of its advantages and disadvantages. withfunctional programmingWith the popularity of the strategic model, the strategic model has begun to be gradually replaced, but it is still worth learning.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/4621.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1
Resource download

Comments0

Cocos系列情怀源码多套精美UI界面皮肤切换全国600子游戏(带控制)
Cocos series emotions source code, multiple sets of exquisite UI interfaces, skin switching across 600 sub-games across the country (with control)
Someone bought it 3 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish