Contents
When do you need to use a strategy pattern?
Use the Strategy pattern 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. The Strategy pattern lets you indirectly alter the object’s behavior at runtime by associating it with different sub-objects which can perform specific sub-tasks in different ways.
How is composition used in the strategy pattern?
The strategy pattern uses composition instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior.
How is the strategy pattern compatible with OCP?
According to the strategy pattern, the behaviors of a class should not be inherited. Instead they should be encapsulated using interfaces. This is compatible with the open/closed principle (OCP), which proposes that classes should be open for extension but closed for modification.
How is the strategy pattern used in validation?
The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication . Typically, the strategy pattern stores a reference to some code in a data structure and retrieves it.
How are algorithms interchangeable in the strategy pattern?
The algorithms are interchangeable, meaning that they are substitutable for each other. The strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime — Wikipedia The key idea is to create objects which represent various strategies.
How is the strategy pattern used in Java?
The Strategy pattern lets you extract the varying behavior into a separate class hierarchy and combine the original classes into one, thereby reducing duplicate code. Use the pattern 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.
How are design patterns used in object oriented programming?
These Design patterns have made a huge impact in the software ecosystem and are used to date to solve common problems faced in Object-Oriented Programming. Let’s formally define the Strategy Pattern: