introduce
In software development, we often encounter such a problem: there can be multiple algorithms or strategies to achieve a certain function, and we choose different algorithms or strategies to complete the function according to the actual situation. Sorting algorithms, for example, can be implemented in a variety of ways.
So, in this case, what should be done? Is to write these algorithms in a class, each method corresponds to a specific sorting algorithm; Again, encapsulate these sorting algorithms in the same method by using if… Else or case statements to select the specific algorithm. Both of these implementations can be called hard coding. Demands, of course, it is possible, but, when a lot of algorithms in a class, the class will become very bloated, maintenance cost will become high, and prone to errors during maintenance, if we need to add or modify the source code of the algorithm class, this will need to move wrapper classes, then it is in violation of the principle of single responsibility and open and close.
If these algorithms and strategies of abstracting, provide a unified interface, different algorithms have different implementation classes or strategy, so that in the client program can by injecting different implementation object or strategy to implement the algorithm of dynamic replacement, the model’s extensibility, maintainability is higher, this is what we learn today strategy pattern.
define
The policy pattern defines a series of algorithms, encapsulates each algorithm and makes them interchangeable, allowing the algorithm to change independently of the customers using it.
Usage scenarios
- Multiple ways of dealing with the same type of problem are only different when specific behaviors are different.
- When you need to securely encapsulate multiple operations of the same type.
- When there are multiple subclasses of the same abstract class and you need to use if-else or switch-case to select the concrete subclass.
UML class diagrams
<figcaption></figcaption>](free.imgsha.com/i/E9ZAp)
- Context: The Context in which the policy is manipulated
- Stragety: The abstraction of strategy
- ConcreteStragetyA, ConcreteStragetyB concrete strategy implementation.
A simple example
Demand: calculate fares for vehicles, general car, medium car, limousine.
/** * public interface ICalculateStrategy {/** * public interface ICalculateStrategyreturn
*/
int calculatePrice(int km);
}
Copy the code
All kinds of cars
// Public class implements ICalculateStrategy {@override public int calculatePrice(int km) {if (km > 0 && km <= 5)
return 5;
if (km > 5 && km <= 7)
return7.if (km > 7 && km <= 10)
return 10;
return10; }}Copy the code
Public class MediumCar implements ICalculateStrategy {@override public int calculatePrice(int km) {if (km > 0 && km <= 5)
return 6;
if (km > 5 && km <= 7)
return9.if (km > 7 && km <= 10)
return12.return12. }}Copy the code
Public class LuxuryCar implements ICalculateStrategy {@override public int calculatePrice(int km) {if (km > 0 && km <= 5)
return 8;
if (km > 5 && km <= 7)
return 13;
if (km > 7 && km <= 10)
return15.return13; }}Copy the code
We are creating a class that operates on Context policies
Public class TransportationCalculator {/** * private ICalculateStrategy ICalculateStrategy = new GeneralCar(); /** * Set policy * @param calculateStrategy */ public voidsetStrategy(ICalculateStrategy calculateStrategy) {
this. iCalculateStrategy = calculateStrategy;
}
public int calcu(int km){
returniCalculateStrategy.calculatePrice(km); }} Copy the codeCopy the code
Testing:
@Test
public void test8(){
TransportationCalculator transportationCalculator = new
TransportationCalculator();
System.out.println("Ordinary car 1 km RMB:" + transportationCalculator.calcu(5));
transportationCalculator.setStrategy(new MediumCar());
System.out.println("Intermediate car 1 km RMB:" + transportationCalculator.calcu(5));
transportationCalculator.setStrategy(new LuxuryCar());
System.out.println("Luxury car 1 km RMB:" + transportationCalculator.calcu(5));
}
Copy the code
Output:
Ordinary car 1 km RMB:5 Intermediate car 1 km RMB:6 Luxury car 1 km RMB:8Copy the code
Have you found that this writing method not only becomes clear structure, but also easy to maintain, scalability is also very strong.
conclusion
The strategy pattern is mainly used to separate algorithms, and there are different concrete implementation strategies under the same behavior abstraction. The open closed principle is well demonstrated in this pattern, that is, defining interface abstractions and injecting different implementations to achieve good scalability.
Advantages:
- Clear structure, simple and intuitive use;
- The coupling degree is relatively low, and the expansion is convenient;
- Operation encapsulation is more complete and data is more secure;
Disadvantages:
- As you add policies, the subclasses become numerous