• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Design pattern: policy pattern, the core idea of Java collection ordering

King Wang

1 月 3, 2022

Preface

During the interview a while ago , An interviewer asked me what design patterns I knew ? I said the strategic model . Then he asked about the scene applications , I answered him again jdk There is a sorting method for the collection tool class of the , That is to say java.util Under bag Collections class , There is one in this class sort Method , We can customize the sorting rules to implement the customized sorting of the collection , This is the most direct application of strategic patterns , After that he nodded , I think I’m quite satisfied with my answer , Of course, I just pretend to be forced on this interview question , After all, at the end of the interview, he said, “please go back and wait for the news.” ….

What is the strategic model

Get down to business , Today we learn the strategic patterns of the design patterns series , First of all, understand its definition .

The strategy pattern , It’s also called the policy model , The idea is : Define a set of algorithms , Encapsulate every algorithm , And make them interchangeable . Its biggest characteristic is that the algorithm can change without affecting the client , To change different functions . Just take what it says sort Method examples , In this method, a Comparator Interface parameters , Yes sort methods , It doesn’t care Comparator The concrete implementation of the interface , As long as the parameters we passed in are of the interface type , thus , We can do it ourselves Comparator Interface , Define the sorting rules we want in the implementation class , For example, to sort a field in ascending or descending order , This is the direct application of strategic patterns .

Write a simple code to express :

public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(20);
list1.add(3);
Collections.sort(list1, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
System.out.println(" Ascending =======" + list1.toString());
Collections.sort(list1, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(" Descending =======" + list1.toString());
}

form

After understanding the definition and examples of policy patterns , Let’s look at the role of the strategic model .

The strategy pattern consists of three roles :

  • Strategy Abstract strategy roles : Strategy 、 The abstraction of algorithm family , Usually interface , Define the methods and properties that each policy or algorithm must have . Use the above set sorting example , The character corresponds to Comparator Interface .
  • ConcreteStrategy Specific strategic roles : Implement operations in abstract strategies , This class contains specific algorithms . That’s what we customized Comparator Implementation class .
  • Context Encapsulate the character : It’s also called contextual roles , Internally, there will be a reference to an abstract role , Call the client . The character corresponds to Collections The tool class itself , In this class hold right Comparator References to interfaces , Can receive our custom concrete implementation class .

Through these three characters , We can simply list the class diagram of the policy pattern :
 Insert picture description here
I can see , The class diagram of the strategy pattern is relatively simple , According to this class diagram , Let’s write its code implementation .

General class code

Abstract strategy roles :

public interface Strategy {
// Algorithmic rules of policy pattern
public void doSomething();
}

Specific strategic roles :

public class ConcreteStrategy1 implements Strategy {
public void doSomething() {
System.out.println(" Specific strategies 1 The algorithm of ");
}
}
public class ConcreteStrategy2 implements Strategy {
public void doSomething() {
System.out.println(" Specific strategies 2 The algorithm of ");
}
}

Encapsulate the character :

public class Context {
// Abstract strategy
private Strategy strategy = null;
// Constructor to set specific policy
public Context(Strategy _strategy) {
this.strategy = _strategy;
}
// The strategy after encapsulation
public void doAnythinig() {
this.strategy.doSomething();
}
}

After building three characters , When the client wants to call , First determine which specific strategy to use , Create the corresponding policy role object , Just pass it on to the encapsulated character , The specific code is as follows :

public class Client {
public static void main(String[] args) {
// Declare a specific strategy
Strategy strategy = new ConcreteStrategy1();
// Declare the context object
Context context = new Context(strategy);
// Perform the method after encapsulation
context.doAnythinig();
}
}

summary

This is the introduction of the strategic model , To say , Strategy mode is a relatively simple design mode , But it is also used more in actual projects , for instance , I used the strategic model in a project of my previous company .

That project belongs to e-commerce system , Every product has its own coupon , When you place an order for the settlement amount, you need to calculate the total price of the goods and coupons , Here’s a headache , Because each type of product has a unique coupon , If you use traditional if/else To judge the type of goods and coupons , Then adding a product or coupon will make the order settlement logic need to be modified , This is obviously not in line with the principle of opening and closing . In this case , We adopt the idea of a strategic model , The code has been modified as follows ,

1、 Define an abstract policy role with product and coupon attributes

2、 At the same time, create specific strategy roles for each type of goods , Define your own unique calculation coupon strategy

3、 In the method of order settlement , Create specific policy objects based on product and coupon types , Pass the object into a encapsulation role and call the settlement amount method

In this way, the corresponding amount can be calculated according to different products and coupons , And the encapsulation of the code becomes more abstract , Commodity specific strategies are independent of each other , Don’t pull one hair and move the whole body , It’s easy and labor-saving .

The above is a specific application of the strategy pattern , Of course , There are many applications of strategic patterns , I will also briefly introduce one of the use scenarios , Through practical examples, let us feel the charm of design mode , After all, a thousand days of military training , the use of the military force is only occasional/temporary , Don’t we learn more theoretical knowledge just to use it in practice one day ?

发表回复