Design Pattern Strategy
https://refactoring.guru/design-patterns/strategy
https://design-patterns.readthedocs.io/zh-cn/latest/behavioral_patterns/strategy.html
Class UML
behavioral design patterns
The Strategy design pattern is one of the behavioral design patterns used to define a family of algorithms, encapsulate each one, and make them interchangeable. The strategy pattern lets the algorithm vary independently from the clients that use it. This pattern is particularly useful for situations where a class needs to perform a specific behavior or service in different ways based on the context or data it is working with.
Key Concepts
Context: The class that uses a Strategy. It is configured with a Strategy object and maintains a reference to the current Strategy object. It may define an interface for setting the strategy.
Strategy: The interface that is common to all concrete strategies. This interface is used by the context to call the strategy defined algorithms.
Concrete Strategies: Implementations of the Strategy interface. Each concrete strategy implements the algorithm using a different approach.
Example Scenario
Imagine you have a Payment class that can process payments in different ways (e.g., credit card, PayPal, Bitcoin). Using the Strategy pattern, you can define a common interface for all payment methods and create separate classes for each payment method.
1 | // Strategy interface |