Skip to main content

39. Strategy Pattern

The Strategy pattern allows selecting an algorithm at runtime.


Example

class Strategy:
def execute(self, data): pass

class UpperCase(Strategy):
def execute(self, data): return data.upper()

class LowerCase(Strategy):
def execute(self, data): return data.lower()

def process(strategy, text):
return strategy.execute(text)

print(process(UpperCase(), "Hello"))

Wrap-Up

Strategy makes it easy to switch behaviors dynamically.