Design Patterns - Strategy Patterns

Recommendations on Design Patterns "Head First Design Patterns" is
the first time I feel that it is a book that explains the profound things in a simple way. After reading it, my doubts are basically clear.


Scenario description:
         In the system payment process, there are different account systems (different third-party channels), and the payment behaviors corresponding to different accounts are inconsistent, but the payment modes are consistent.

Example:
User payment account:

UserA A account system (Yibao account)
UserB B account system (Lianlian payment)
UserC C account system (UMPA)


Corresponding orders:

Order_A, Order_B, Order_C

Description:
      User A/B/C purchases wealth management products After that, the orders Order_A/Order_B/Order_C are generated respectively, and each order needs to be paid. Since ABC corresponds to the account types of different payment channels, the overall mode is the same, but each payment channel has its own special processing. If you use programming If the interface of a payment channel is changed, the company's products will follow the change, and all payment channels in one place will be affected.

Strategy Pattern
    Using strategy pattern can have a good solution to the above problems.
// schema superclass
public abstract Order{
  //payment behavior
  public PayBehavior payBehavior; (programming for the interface)
  //payment action
  pbulic void pay(){
    payBehavior.pay();
   }
  / / Load the strategy interface implementation class object
  puoblic void setPayBehavior(PayBehavior payBehavior){
        payBehavior = payBehavior
  }

}

Policy interface:

public Interface PayBehavior {

   public void pay();//Payment interface
}


Strategy interface implementation:

public class Apay implements PayBehavior {
     public void pay(){
      sysout("A pay");
     }
}

public class Bpay implements PayBehavior {
     public void pay(){
      sysout("B pay");
     }
}

public class Cpay implements PayBehavior {
     public void pay(){
      sysout("C pay");
     }
}

Policy Object:

public class OrderPlot extends Order{
   //Construct normally

}

test:

public class Test{

    public static void main(String[] args){
     // Construct the strategy object
     Order order = new OrderPlot();
     //Load policy interface
           order.setPayBehavior(new Apay());
     // strategy method execution
           order.pay();
    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326687025&siteId=291194637