Definition of policy patterns

The policy pattern belongs to the behavior pattern.

The strategy pattern

The policy pattern encapsulates a series of algorithms into corresponding classes, and these classes implement the same interface and can be replaced with each other. In the policy mode, the calling algorithm is encapsulated in the encapsulation class Context. Abstract Strategy Strategy is generally an interface for defining specifications, which generally does not contain logic. In fact, this is only a general implementation, but in actual programming, because there is inevitably some same logic between each specific Strategy implementation class, in order to avoid repeated code, we often use abstract classes to act as the role of Strategy, and encapsulate the common code inside.

The policy mode applies to the following scenarios: The notification service supports internal notification, SHORT message notification, and email notification. Depending on your needs, you may use any of three approaches. In this scenario, the policy mode can be used, and the client can choose according to the requirements.

Structure of policy patterns

  • Environment class: Secondary encapsulation of policies to avoid direct invocation of policies by higher-level modules.
  • Abstract policy: Typically an interface, the policy pattern looks more like the template method pattern when an abstract class is used to encapsulate a common piece of code when there is repeated logic in various implementation classes.
  • Concrete policy: The concrete policy role is typically filled by a set of classes that encapsulate the algorithm and are freely interchangeable as needed.

Advantages of the strategic pattern:

  • Users can select algorithms or behaviors without modifying the original system, or flexibly add new algorithms or behaviors, which provides a way to manage related algorithm families.
  • Multiple conditional statements can be avoided. Multiple conditional statement is not easy to maintain, it takes which algorithm or take which behavior of the logic and algorithm or behavior of the logic mixed together, all listed in a multiple conditional statement, than the use of inherited methods but also primitive and backward.

Disadvantages of the strategic pattern:

  • All policy classes must be exposed to the client (caller) because it is up to the client to decide which policy to use, so the client should know what the policies are and the differences between them, otherwise the consequences can be severe. For example, if a client wants to use a container, both a list implementation and an array implementation, does the client need to understand the difference between a list and an array? In this case, it violates Demeter’s law.
  • Because the policy pattern encapsulates each specific policy implementation as a separate class, the number of objects can be significant if there are many alternative policies.

Practice of strategy patterns

Notification interface, abstract policy class implementation:

public interface Notify {
    // strategy method
    public void notice(a);
}
Copy the code

Context implementation:

public class Context {
    // The object that holds a specific policy
    private Notify notify;
    // The constructor passes in a concrete policy object
    public Context(Notify notify){
        this. notify = notify;
    }
    // strategy method
    public void contextInterface(a){ notify.notice(); }}Copy the code

Implementation of mail notification policy class:

public class MailNotify implements Notify {
    @Override
    public void notice(a) {
        // Related business}}Copy the code

Implementation of SMS notification strategy class:

public class SMSNotify implements Notify {
    @Override
    public void notice(a) {
        // Related business}}Copy the code

The client invokes the SMS notification policy:

public class Client {
    public static void main(String[] args) {
        // Select and create a policy object to use
        Notify strategy = new SMSNotify();
        // Create environment
        Context context = new Context(strategy);
        // Call from the Contextcontext. contextInterface(); }}Copy the code

conclusion

The focus of the strategy pattern is not on how to implement algorithms, but how to organize and invoke those algorithms so that the program structure is more flexible, more maintainable, and more extensible. At run time, the policy pattern can use only one specific policy implementation object at a time, and while it can dynamically switch between different policy implementations, only one can be used at a time. It is common to see that all concrete policy classes have some common behavior. At this point, these common behaviors should be placed in the common abstract policy role Strategy class. Of course, the abstract policy role must be implemented using Java abstract classes, not interfaces.

Applicable scenarios:

  • 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.

Vs Factory Mode

The factory pattern is the creation pattern, which focuses on object creation and provides an interface for creating objects. Make object creation independent of the specific user. The policy pattern is the object behavior pattern, which focuses on the encapsulation of behavior and algorithm. It defines a series of algorithms, encapsulates each algorithm, and makes them interchangeable. Allows the algorithm to change independently of the customers that use it.

Vs template method pattern

Another mode also focuses on the encapsulation of algorithms — template method mode. Comparing with the class diagram, it can be seen that the only difference between the policy mode and template method mode is that a separate wrapper class Context is added, which differs from the template method mode in that: In the template method mode, the calling body of the algorithm is in the abstract parent class, while in the policy mode, the calling body of the algorithm is encapsulated in the wrapper class Context. Abstract Strategy Strategy is generally an interface, which only aims to define the specification, and generally does not contain logic. In fact, this is only a general implementation, but in actual programming, because there is inevitably some same logic between each specific Strategy implementation class, in order to avoid repeated code, we often use abstract class to play the role of Strategy and encapsulate the common code inside. Therefore, in many application scenarios, You will generally see the shadow of the template method pattern in policy pattern.

Subscribe to the latest articles, welcome to follow my official account

reference

  1. 23 Design Patterns (12) : Strategic patterns
  2. Design Pattern (18) Strategy pattern (object behavior type)