What is the ghost of Java strategy mode? Ha ha ha ha ha school younger sister tell me how tact face of I stay!

๐Ÿงพ1. What exactly is strategic mode?? ๐Ÿ‘€

The policy pattern belongs to the behavior pattern of an object. The idea is to take a set of algorithms and encapsulate each one into a separate class with a common interface, making them interchangeable. The policy pattern allows the algorithm to change without affecting the client.

In simple terms, the policy pattern represents a generic solution for a class of algorithms, and you can choose which solution to use at runtime.

The focus of the strategy pattern ๐Ÿ“š

The focus of strategy pattern is not how to implement algorithms, but how to organize and call these algorithms, so as to make the program structure more flexible, with better maintainability and scalability.

Equality of the algorithm ๐Ÿ“š

A great feature of the strategy pattern is the equality of each strategy algorithm. For a series of specific strategy algorithms, the status is the same, so the algorithm can be implemented to replace each other. All the strategy algorithms are independent of each other in implementation, there is no dependence on each other. So this series of policy algorithms can be described as follows: Policy algorithms are different implementations of the same behavior. [Obtain information]

Uniqueness of runtime policy ๐Ÿ“š

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.

Public behavior ๐Ÿ“š

It is common to see that all specific policies have some common behavior. At this point, these common behaviors should be placed in a common abstract policy role

Strategy class. Instead of using interfaces, you should use abstract classes.

๐Ÿงพ2. Structure of the policy pattern

The policy pattern consists of three parts :(as shown below)

  • A. One or more customers using policy objects.(Environment Role)

  • B. An interface representing an algorithm, which is the interface of the policy pattern.

  • C. One or more concrete implementations of the interface that represent multiple implementations of the algorithm.

๐Ÿงพ3. Application of policy mode

ใ€€

  • A. Fault tolerant recovery mechanism. When the program is running, if some kind of error occurs, the system will not directly hang down or affect other function points of the system. It is that the system tolerates such errors and provides a fault-tolerant recovery mechanism in advance to keep the program running properly.

ใ€€

  • Such as: A system for all the logging operation, and left logging library, convenient and subsequent use, but at the time of left logging library, errors may occur, such as database problems, it can record in the file first, wait for database problem to repair, then the log records in the file synchronization in the database.ใ€ References ใ€‘

For such functional design, a strategic design pattern can be used to dynamically switch during runtime as needed.

ใ€€

  • B. Suppose we design a shopping system with membership mechanism, which provides 20% discount for all SVIPs of the system, 10% discount for all VIPs of the system, and no discount for non-members. So for such system function design, can also adopt the strategy mode to design.

ใ€€

  • C. Using different criteria (weight or color, etc.) to screen items in inventory can be applied to a wider range of fields, such as using different criteria to verify the validity of input, and using different ways to analyze or format input.

๐Ÿงพ4. Policy mode Demo

Suppose that you need to select appropriate policies for processing the parameters sent by the call interface based on service requirements. In this case, policy 1 and policy 2 are assumed.

Client:

/** * @author lyh * @version v-1.0.0 * @since 2021/6/2 */
public class Client {
    public static void main(String[] args) {
        // Customers choose their own policies based on their needs
        // Join Java development chat
        // Select strategy 1
        StrategyObj strategyOne = new StrategyObj(new StrategyOne());
        System.out.println(strategyOne.strategy("one"));
        // Select strategy 2
        StrategyObj strategyTwo = new StrategyObj(new StrategyTwo());
        System.out.println(strategyTwo.strategy("two")); }} Output: Execute policy1! Execution strategy2!

Process finished with exit code 0
Copy the code

Policy interface:

/** * @desc: policy interface */
public interface Strategy {
    String execute(String s);
}

/** * @desc: policy interface encapsulation */
public class StrategyObj {

    private final Strategy strategy;

    public StrategyObj(Strategy v) {
        this.strategy = v;
    }

    public String strategy(String s) {
        return strategy.execute(s);
    }// Join Java development chat

}
Copy the code

Policy implementation:

/** * @desc: */
public class StrategyOne implements Strategy {
    @Override
    public String execute(String s) {
        return "Execute Strategy 1!"; }}/** * @desc: */
public class StrategyTwo implements Strategy {
    @Override
    public String execute(String s) {
        return "Execute Strategy 2!"; }}Copy the code

๐Ÿงพ5. Use Lambda expressions

From the demo above, you should realize that Strategy is a functional interface; In addition, it has the same function description as Predicate

. This means that instead of declaring new classes to implement different policies, we can achieve the same goal and be more concise by passing Lambda expressions directly.


public class Client {
    public static void main(String[] args) {
        StrategyObj strategyOne = new StrategyObj((String s) -> {return "Execute Strategy 1"; }); System.out.println(strategyOne.strategy("one"));
         // Join Java development chat
        StrategyObj strategyTwo = new StrategyObj((String s) -> {return "Execute Strategy 2"; }); System.out.println(strategyTwo.strategy("two")); }}Copy the code

Lambda expressions avoid rigid template code when using policy design templates. A closer look at the code shows that Lambda expressions actually encapsulate the policy, which is why the policy design pattern was created.

๐Ÿงพ6. Advantages and disadvantages of strategic patterns

advantages

  • A. Use the policy pattern to avoid using multiple conditions if… else if… Else statements, multiple conditions are not easy to maintain and the code is not readable.

  • B. The policy pattern provides a way to manage related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. Proper use of inheritance can avoid code duplication by moving common code into a parent class.


disadvantages

  • A. The client must know all policy classes and decide which policy class 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 the algorithm or behavior.

  • B. Since the policy pattern encapsulates each specific policy implementation as a separate class, the number of objects can be large if there are many alternative policies.

In the end, I wish you all success as soon as possible, get satisfactory offer, fast promotion and salary increase, and walk on the peak of life.

If you can, please give me a three link to support me yo ๐Ÿง๐Ÿง๐Ÿง