Lesson 2 - The Strategy Pattern
The Strategy Pattern is a Behavioural Design Pattern.
Behavioural Design Patterns are design patterns that identify common communication patterns among objects and realise these patterns and in doing so increases flexibility, carrying out this communication.
Definition
The Strategy Pattern defines a family of algorithms, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
When to use ?
When you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.
When you have a lot of similar classes that only differ in the way they execute some behaviour.
To isolate the business logic of a class from the implementation details of algorithms that may not be as important in the context of that logic.
When your class has a massive conditional operator that switches between different variants of the same algorithm.
Important to Note
One of the dominant strategies of object oriented design is the "Open-Closed principle".
The Strategy pattern suggests that you take a class that does something specific in a lot of different ways and extract all of these algorithms into separate classes called strategies.
Favour composition over inheritance!
Program to an interface and not an implementation.
Identify the parts that vary and separate them from the parts that stay the same.
Benefits
- You can swap algorithms used inside an object at runtime.
- You can isolate the implementation details of an algorithm from the code that uses it.
- You can replace inheritance with composition.
- Open/Closed Principle. You can introduce new strategies without having to change the context.
Code Examples
Duck Example
Street Fighter Example
Payment Example
Sort Example
Links
https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial
https://blog.bitsrc.io/keep-it-simple-with-the-strategy-design-pattern-c36a14c985e9
https://www.geeksforgeeks.org/strategy-pattern-set-1/
https://refactoring.guru/design-patterns/strategy
https://www.youtube.com/watch?v=SicL4fYCz8w
https://www.youtube.com/watch?v=QZIvlny1Onk
https://www.youtube.com/watch?v=Nx8iUv-ZnPw
More Reading
Next Up - The Decorator Pattern
Comments
Post a Comment