Strategy Pattern enables an algorithm’s behavior to be selected at runtime. It provides a way to define a family of algorithms, encapsulate each one as an object (one strategy), and make them interchangeable to carry out some specific behavior.
Think about now you want to go out, you can choose to take a bus or call a Taxi, you could even take a bus firstly and then change to a bike. The Strategy Pattern is to be used for this situation where you want to choose the algorithm/strategy to use at run-time.
In fact, we could choose
if else to realize this. But this will cause the following problems:
- Every time you add a new strategy, you need to change the code on client side. So adda new
- Many “If … else …” in your code cause maintenance to be difficult.
So Strategy Pattern is here to help you add and choose an algorithm/strategy.
When Use Strategy Pattern
1, If your system in which there are many classes, the only difference between them is their behaviors, then use the strategy pattern can be dynamically allows to choose a behavior.
2, If your system needs to dynamically select one of several algorithms.
Strategy defines an interface for all supported strategy. Context uses this interface to call the strategy defined by a ConcreteStrategy.
ConcreteStrategy is each concrete strategy simple implementing
Context has a reference of
Strategy. It separates strategy itself and its duty (How it should be used). Client will use Context to add/change one Strategy. And Client can swap ConcreteStrategys in and out without effecting our Context.
For more details,
Context receives requests from the client and delegates them to the strategy object. Usually
ConcreteStartegy is created by the client and passed to
Context. From this point the clients interacts only with
Context. So a new strategy can not effect that much on Client. A Client only needs to know those Strategies already existing.
Now we want to sort something. There are three strategys to choose:
- Bubble Sort
- Insertion Sort
- Selection Sort
Client to test: