Definition of Strategy

A series of algorithms are defined and each algorithm is encapsulated so that they can be replaced with each other without affecting the customers using the algorithm.

This definition is abstract and I copied it. After talking for a long time, it seems very strong, but I don’t know what I mean. Now let’s use specific examples to make concrete understanding.

How to understand

When it comes to policy, interface is indispensable. The core is to abstract our policy into a policy interface, and then implement different types of policies based on the policy interface. Finally, we need an environment to carry out the policy.

In fact, the core can be divided into three parts:

1. Policy Abstract interface 2. Policy Abstract interface implementation class 3

The advantage of this design is that the abstract interface does not need to be modified, and the host class does not need to be modified. We only need to extend the implementation class of the policy interface. Meet the open and close principle.

For example

Give an abstract policy interface to attack

@FunctionalInterface
public interface Attack<T> {
    void doAttack(T t1,T t2);
}
Copy the code

Define a hero entity with some basic attributes

import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Hero {

    private String name;
    /** * Damage */
    private Integer AP;

    /** * Health */
    private Integer HP;

    /** * Mana */
    private Integer MP;
}

Copy the code

Define a battlefield environment as a vehicle for executing attack strategies.

public class Battlefield<T> {

    public void fight(Attack<T> attack, T t1, T t2) {
        System.out.println();
        System.out.println("Initial battle platform");
        System.out.println(t1+"Into the field");
        System.out.println(t2+"Into the field");
        attack.doAttack(t1, t2);
        System.out.println(Initial attack is over.); System.out.println(); }}Copy the code

Abstract strategies can be implemented in several ways:

  1. Define different class inheritance implementations
  2. Directly implemented internally at the time of invocation
  3. Functional programming
public class Strategy {

    public static void main(String[] args) {
        Battlefield battlefield =new Battlefield();
        Hero hero1=new Hero("Galen".4.10.30);
        Hero hero2=new Hero(",".2.50.90);
        battlefield.fight((Attack<Hero>) (t1, t2) -> System.out.println(t1.getName()+"To"+t2.getName()+"Caused by using whirlwind."+t1.getAP()+"Dot damage"),hero1,hero2);

        battlefield.fight((Attack<Hero>) (t1, t2) -> System.out.println(t1.getName()+"To"+t2.getName()+"The use of justice has resulted in"+t1.getAP()*10+"Dot damage"),hero1,hero2);

        battlefield.fight((Attack<Hero>) (t2, t1) -> System.out.println(t2.getName()+"To"+t1.getName()+"Caused by the use of a ruthless iron hand."+t2.getAP()*3+"Dot damage"),hero2,hero1); }}Copy the code

Here, the blogger uses functional programming to realize three different strategies, and the final operation effect is as follows:

How to use

Advantages:
  1. Make the program more maintainable. Avoid a large number of if and else statements in multiple cases,
  2. In line with the open and close principle. You can add algorithms flexibly without modifying the original code.
  3. High cohesion and low coupling. Put the use of the algorithm in the environment class and the implementation of the algorithm in the policy interface implementation.
Disadvantages:
  1. This can result in a large number of policy interface implementation classes
  2. Consumers must know when to use the appropriate policy class
To use:

In application, we need to determine whether the current scenario meets the conditions for using the strategy pattern:

  1. Whether there are policies (algorithms or methods) that can be abstracted
  2. Whether it is necessary to abstract, and whether it is often necessary to expand after abstraction

The use of strategic patterns when necessary is a beauty of design, but not every scenario needs to apply strategic patterns, thoughtless application can increase maintenance costs.

Application of the JDK to the policy pattern

So the JDK also uses the policy pattern in its design. For example, the Comparator interface is a typical policy interface, which allows us to define arbitrary comparison rules. Arrays.sort() is a host environment class for specific comparison strategy algorithms that sorts your collections and comparison algorithms. The comparison strategy here is the part where we can flexibly extend customization.

conclusion

There are only three things you need to keep in mind for strategic patterns. Here I repeat:

1. Policy Abstract interface 2. Policy Abstract interface implementation class 3

In the actual development of flexible thinking to use. But remember to only use it when you have to, not when you have to.

I hope this article is helpful to you, and welcome to add personal wechat dyingGQ to exchange and learn ~~

I am aDying strandedI have been looking forward to meeting you. Whether you expect it or not, tide goes up and down, I’m just here…

See you next time