Strategy#

The Strategy pattern is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside the original context object. The original object, called context, holds a reference to a strategy object and delegates it executing the behavior. In order to change the way the context performs its work, other objects may replace the currently linked strategy object with another one.

UML Diagram#

+-------------------+        +-------------------+
|    Context        |<-------|  ConcreteContext  |
|-------------------|        |-------------------|
| +setStrategy()    |        | +setStrategy()    |
| +executeStrategy()|        | +executeStrategy()|
+-------------------+        +-------------------+
        ^                           ^
        |                           |
+-------------------+        +-------------------+
|    Strategy       |        |  ConcreteStrategy |
|-------------------|        |-------------------|
| +execute()        |        | +execute()        |
+-------------------+        +-------------------+

In this diagram, Context is an interface with methods setStrategy() and executeStrategy(). Strategy is an interface with the method execute(). ConcreteContext and ConcreteStrategy are classes that implement the Context and Strategy interfaces, respectively. The arrows indicate that the ConcreteContext and ConcreteStrategy classes inherit from the Context and Strategy interfaces.

--- Java Example ---
--- Python Example ---