Different with using abstract class
there is a difference between using the Strategy pattern and having an abstract method that all child classes inherit from. The key distinction lies in how the algorithms or behaviors are encapsulated and how they are used or changed at runtime.
Abstract Method in Inheritance
When you use an abstract method in a base class that all child classes inherit and implement, you are defining a fixed set of behaviors that are tied to the specific classes. This approach is static and the behavior is determined at compile time.
Example
Strategy Pattern
The Strategy pattern encapsulates each algorithm (or behavior) in a separate class and makes them interchangeable. The main benefit is that you can change the algorithm used by the context object at runtime.
Example
Differences
Flexibility at Runtime:
Abstract Method: The behavior is defined at compile time and cannot be changed dynamically.
Strategy Pattern: The behavior can be changed at runtime by setting a different strategy.
Encapsulation:
Abstract Method: The behavior is encapsulated in the derived classes, which are tied to a specific type hierarchy.
Strategy Pattern: The behavior is encapsulated in separate strategy classes, promoting composition over inheritance.
Open/Closed Principle:
Abstract Method: Adding new behaviors requires modifying the class hierarchy, potentially violating the open/closed principle.
Strategy Pattern: New behaviors can be added by creating new strategy classes without modifying existing ones, adhering to the open/closed principle.
Reusability:
Abstract Method: Behaviors are tied to the specific class hierarchy and may not be easily reusable outside of it.
Strategy Pattern: Behaviors are encapsulated in independent strategy classes that can be reused by different contexts.
Last updated