This is the 16th day of my participation in the August More Text Challenge

Java Design Patterns – Policy patterns, take a look, let’s make a good preparation for the next step !!!!

Will be a review ya, will not come to see it together.

Like a sentence: “eight hours for life, eight hours for development”.

If you like it, let’s stick to it!!

‘😁

Cover: I think this is summer, summer in my mind

Design Mode series:

  • Java Design pattern – singleton pattern
  • Java Design Pattern – Factory Pattern (1) Simple Factory pattern
  • Java Design Pattern – Factory Pattern (2) Factory method pattern
  • Java Design Pattern – Factory Pattern (3) Abstract Factory pattern
  • Java Design pattern – Builder pattern
  • Java Design pattern – Proxy pattern
  • Java Design pattern – Adapter pattern
  • Java Design pattern – Decorator pattern
  • Java Design pattern – Bridge pattern
  • Java Design pattern – Appearance pattern
  • Java Design pattern – Composite pattern
  • Java Design pattern – Share meta pattern
  • Java Design Pattern – Template method pattern
  • Java Design pattern – Policy pattern
  • Java Design pattern – Chain of Responsibility pattern
  • Java Design Pattern – The Mediator pattern
  • Java Design Pattern – Observer Pattern (publish/subscribe pattern)
  • Continuously updated…

One, foreword

1) Introduction:

In real life, there are often many strategies to achieve a certain goal. For example, today’s homework should be written by this girlfriend or that girlfriend? It’s a tough choice. Forget it. Just do it yourself. (There is no 😂). Text: For example, you can travel by plane, train, bike or drive your own car, etc., and supermarkets can offer discounts, goods and points for promotion.

Programming must be known, when there are many algorithms to achieve a certain function or strategy, we can choose according to different environment or conditions of different algorithms or strategies to complete the function, such as write a sorting algorithm, we can select the binary tree sort, quick sort, heap sort, etc., according to the different given conditions, choose the most appropriate sorting algorithm.

And we as a program ape, development needs to choose a development tool, of course, there are many tools for code development, you can choose Idea for development, you can also use Eclipse for development, you can also use some other development tools.

2) Overview:

As a software design pattern, policy pattern refers to a certain behavior of the object, but in different scenarios, the behavior has different implementation algorithms.

Definition of a Strategy pattern: This pattern defines a series of algorithms and encapsulates each algorithm so that they are interchangeable and changes to the algorithm do not affect the customers using the algorithm. The policy pattern belongs to the object behavior pattern. It encapsulates the algorithm, separates the responsibility of using the algorithm from the implementation of the algorithm, and assigns different objects to manage these algorithms.

3) Role Structure:

The main roles of the policy pattern are as follows.

  1. Abstract Strategy Class: This is an abstract role, usually implemented by an interface or abstract class. This role gives all the interfaces required by the specific policy classes.
  2. Concrete Strategy class: Interfaces that implement abstract policy definitions and provide Concrete algorithm implementations.
  3. Context class: Holds a reference to a policy class that is ultimately called by the client.

4) Usage Scenarios:

1. Multiple classes differ only in their behavior. The Strategy mode can be used to dynamically select the specific behavior to be executed at runtime.

2. Different strategies (algorithms) need to be used in different situations, or policies may be implemented in other ways in the future.

3. Hide the implementation details of specific strategies (algorithms) from customers, completely independent of each other.

4. If an object has many behaviors, these behaviors can be implemented using multiple conditional selection statements without appropriate patterns.

5) Precautions:

If a system has more than four policies, you need to consider using mixed mode to solve the problem of policy class inflation.

Ii. Case code

2.1 Cases:

Promotional activities

A department store is planning its annual promotion. Launch different promotional activities for different festivals (Spring Festival, Mid-Autumn Festival, Christmas), and the promoters will show the promotional activities to customers.

Class diagram:

2.2. Implementation:

Common interface for all promotions in Dingyi Department Store

public interface Strategy {
    void show(a);
}
Copy the code

Concrete Strategy: Specific promotions for each holiday

// Promotional activities for the Spring Festival
public class StrategyA implements Strategy {

    public void show(a) {
        System.out.println("Spring Festival Activity: Buy one get one free"); }}// Promotional activities for Mid-Autumn Festival B
public class StrategyB implements Strategy {

    public void show(a) {
        System.out.println("Mid-Autumn Festival Activity: $50 off $200"); }}// Promotional activities for Christmas
public class StrategyC implements Strategy {

    public void show(a) {
        System.out.println("Christmas activity: Over $1000 + $1 for any goods under $200"); }}Copy the code

Define Context: Used to connect the Context, that is, to sell the promotion to the customer, in this case, the salesperson

public class SalesMan {
    // Holds a reference to the abstract policy role
    private Strategy strategy;                 
                                               
    public SalesMan(Strategy strategy) {       
        this.strategy = strategy;              
    }                                          
                                               
    // Show promotions to customers
    public void salesManShow(a){ strategy.show(); }}Copy the code

Client:

public class Client {

    public static void main(String[] args) {
        SalesMan salesMan = new SalesMan(new StrategyA());
        salesMan.salesManShow();
        System.out.println("-- -- -- -- -- -- -- -- -- -- -");
        SalesMan salesManB = new SalesMan(new StrategyB());
        salesManB.salesManShow();
        System.out.println("-- -- -- -- -- -- -- -- -- -- -");
        / * * * Spring Festival activities: buy one get one free * -- -- -- -- -- -- -- -- -- -- - * Mid-Autumn festival activities: full 200 yuan to 50 yuan * -- -- -- -- -- -- -- -- -- -- - * /}}Copy the code

Third, summary

Advantages:

  1. The policy pattern can provide different implementations of the same behavior, and customers can choose different ones based on different time or space requirements.
  2. The policy pattern provides perfect support for the open closed principle, allowing for the flexibility of adding new algorithms without modifying the original code.
  3. Multi-conditional statements are difficult to maintain, and using policy patterns can avoid multi-conditional statements, such as if… Else statement, switch… A case statement.
  4. The policy pattern provides a way to manage related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. Inheritance can be used properly to move common code into a parent class, thereby avoiding duplicate code.

Disadvantages:

  • The client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms in order to choose the right algorithm class at the right time. In other words, the policy pattern only works if the client knows all the algorithms or behaviors.

  • The policy pattern creates many policy classes, and each concrete policy class generates a new class. Policy classes can sometimes be designed to be shareable by storing environment-dependent state in clients, so that instances of policy classes can be used by different clients. In other words, you can use the share pattern to reduce the number of objects.

4. Talk to yourself

I do not know whether the article is useful or useless, just want to do a share. I hope you can enjoy it and have a good harvest here.

Of course, THERE’s no denying that I want to get that kind of pleasure from other people’s approval and keep it going.

Hello, be happy every day. See you in the next article.

This series is still being updated…. I’ll be back for sure. 😁