This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
An overview of the
A Strategy Pattern is a series of algorithms encapsulated by some independent classes that can be transformed from one another. Each algorithm is called a Policy or Policy, so it is also called Policy Pattern, which is an object behavior Pattern.
Strategy pattern of main purpose is to separate the definition and use of algorithm, which is separate behavior and environment of the algorithm, in order to ensure that these strategies when use consistent, typically provide an abstract strategy class to do rule definition, while each algorithm corresponding to a specific strategy, using the algorithm of environment is to abstract strategy programming.
structure
- Context (Context class) : is the role that uses the algorithm and maintains a reference to the abstract policy class.
- Strategy (Abstract Policy Class) : Declares the common methods of all concrete policy classes, usually abstract classes or interfaces, but can also be concrete classes.
- ConcreteStrategy: Implements an algorithm declared in an abstract policy class.
advantages
- Separating the definition and use of policies facilitates separation of concerns.
- It avoids the use of multiple judgment conditions and is beneficial to the maintenance of the system.
- The new policy does not need to modify the environment class, and complies with the open and closed principle.
- The environment class of the policy pattern uses policies by aggregation, reducing the use of inheritance.
- Abstract policy classes provide a mechanism for algorithm reuse, avoiding duplicate code.
disadvantages
- When there are too many policies, class bloat results.
- All strategy classes need to be exposed, not according to Demeter’s law.
- You cannot combine multiple policy classes on the client side.
Application scenarios
- The system needs to dynamically select one of several algorithms.
- The system needs specific rules for masking algorithms.
- In scenarios where multiple classes differ only slightly in algorithm or behavior, the policy pattern avoids the use of multiple conditional selection statements that are difficult to maintain.
Applications in the JDK
The Java.util.parator JDK uses the policy pattern.
Java.util.Com parator is an abstract policy class:
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
Copy the code
Java.util. Arrays is the environment class:
public class Arrays {
public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) {
sort(a);
} else {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null.0.0); }}}Copy the code