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

1. An overview of the

The policy pattern defines a family of algorithms (a set of behaviors) that are packaged separately so that they can be replaced with each other, making changes to the algorithm independent of the customers using the algorithm.

Structure of 2.

Policy pattern UML

The policy mode contains the following roles:

  • Context: Holds a reference to a Strategy class
  • Abstract Policy Class (Strategy) : An abstract role, implemented by an interface or abstract class. Provides all the interfaces required by the specific policy classes.
  • ConcreteStrategy class: encapsulates related algorithms or behaviors.
/ / environment
public class Context {
  private Strategy strategy;
  /** * policy method **/ 
  public void contextInterface(a) { strategy.strategyInterface(); }}// Abstract policy class
abstract public class Strategy {
  /** * policy method **/ 
  public abstract void strategyInterface(a);
}

// Concrete policy class
public class ConcreteStrategy extends Strategy {
  /** * policy method **/ 
  public void strategyInterface(a) {
    // Method concrete implementation}}Copy the code

Example 3.

We sell our goods to different customers, at different volumes, at different prices

  • New customers sell in small quantities
  • New customers sell in large quantities
  • Regular customers sell in small quantities
  • Regular customers sell in large quantities

The specific use of which quotation strategy, according to the actual situation to confirm the simplest writing is if else:

if(type.equals("Small volume sales for new customers")){
 System.out.println("Full price");
 return price*1;
}else if(type.equals("Mass sales for new customers.")){
 System.out.println("10% off.");
 return price*0.9;
}else if(type.equals("Regular customers sell in small quantities")){
 System.out.println("20% off.");
 return price*0.8;
}else if(type.equals("Regular customers sell in bulk.")){
 System.out.println("20% off.");
 return price*0.7;
}
Copy the code

Write code using policy patterns

3.1 Define an interface to represent a quote

public interface Strategy {
    public double getPrice(double stardardPrice);
}
Copy the code

3.2 Define a policy

There is a 20% discount for regular users

public class OldCustomerManyStrategy implements Strategy {

    @Override
    public double getPrice(double stardardPrice) {
        System.out.println("20% off");
        return stardardPrice*0.8; }}Copy the code

New users get a 9 discount

public class NewCustomerManyStrategy implements Strategy {

    @Override
    public double getPrice(double stardardPrice) {
        System.out.println("10% off.");
        return stardardPrice*0.9; }}Copy the code

3.3 Implementing a Context

To manage quotes, the client interacts directly with the context

public class Context {
    private Strategy strategy;

    public Context(Strategy strategy){
        this.strategy = strategy;
    }
    public Strategy getStrategy(a) {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void pringPrice(double s){
        System.out.println("What should be quoted is:"+strategy.getPrice(s)); }}Copy the code

3.4 Client Client Invocation

The client selects a policy, passes it to the Context, and the Context executes it

public class Client {
    public static void main(String[] args){
        Strategy strategy = new OldCustomerFewStrategy();
        Context context = new Context(strategy);
        context.pringPrice(998); }}Copy the code

4. Advantages & Disadvantages

4.1 the advantages

  • The policy pattern provides perfect support for the “open closed principle”, allowing users to choose algorithms or behaviors without modifying the existing system, or to flexibly add new ones.
  • The policy pattern provides a way to manage related algorithm families.
  • The policy pattern provides an alternative to inheritance.
  • Use policy patterns to avoid multiple conditional transition statements.

4.2 disadvantages

  • The client must know all the policy classes and decide which one to use.
  • The policy pattern will result in many policy classes.

4.3 Applicable Environment

  • If there are many classes in a system that are distinguished only by their behavior, then using the policy pattern dynamically allows an object to choose one behavior among many behaviors.
  • A system needs to dynamically choose one of several algorithms.
  • If an object has many behaviors, those behaviors can be implemented using multiple conditional selection statements without proper patterns.
  • You do not want the client to know complex data structures related to the algorithm. Encapsulate the algorithm and related data structures in a specific policy class to improve algorithm confidentiality and security.

5. Application of policy pattern

Four rejection policies for thread Pool ThreadPoolExecutor, and we can customize the thread pool rejection policies.

  • AbortPolicy throws an exception directly
  • CallerRunsPolicy only invokes the caller’s thread
  • DIscardOldestPolicy Discards the most recent task in the queue
  • DIscardPolicy Discards the card

conclusion

The strategy pattern is a design pattern that is easy to understand and use. The strategy pattern is the encapsulation of the algorithm, which separates the responsibility of the algorithm from the algorithm itself and delegates it to different objects to manage. Policy patterns usually encapsulate a set of algorithms into a set of policy classes as a subclass of an abstract policy class. In a word, “Prepare a set of algorithms and encapsulate each one so that they are interchangeable.”

In the policy pattern, it is up to the client to decide which specific policy roles to use in what situations. Policy mode only encapsulates the algorithm, providing convenience for new algorithms to be inserted into the existing system and old algorithms to be “retired” from the system. Policy mode does not decide when and which algorithm to use. The algorithm selection is up to the client. This improves the flexibility of the system to some extent, but the client needs to understand the differences between all the specific policy classes in order to choose the appropriate algorithm, which is also one of the disadvantages of the policy pattern, which increases the difficulty for the client to use to some extent.

This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.