CodeBlanks Logo Icon CodeBlanks

Strategy

Learn the Strategy pattern.

Strategy

The Strategy pattern defines different methods of an operation as callable objects; the client picks one at runtime. In Python, functions are naturally callable, so using functions as strategies is easy.

def add(a, b):
    return a + b

def mul(a, b):
    return a * b

def calculate(strategy, a, b):
    return strategy(a, b)

print(calculate(add, 3, 4))  # 7
print(calculate(mul, 3, 4))  # 12

Strategy turns conditional branches (if/elif) into callable objects; this makes the code easier to extend.

Function strategies

In Python, functions are first-class objects; they can be passed as parameters and stored in a list. This makes the Strategy pattern easy to apply.

strategies = [add, mul, lambda a, b: a - b]
for s in strategies:
    print(s(10, 3))  # 13, 30, 7

A class-based strategy is also possible; however, a function is usually shorter and more readable.

Practice Calculate with Strategy

Define def add(a, b): and def mul(a, b): (add does return a + b, mul does return a * b). Write def calculate(strategy, a, b): that does return strategy(a, b). Print the results with print(calculate(add, 3, 4)) and print(calculate(mul, 3, 4)).

Starter code

main.py
# define add and mul functions
# write calculate: it calls the strategy parameter
# call calculate with add and mul strategies, print the results

Sample solution

main.py
def add(a, b):
    return a + b

def mul(a, b):
    return a * b

def calculate(strategy, a, b):
    return strategy(a, b)

print(calculate(add, 3, 4))
print(calculate(mul, 3, 4))

Expected output

7
12

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Strategy concepts

Term Meaning
strategy parameter Is callable
add, mul Are strategy functions
calculate(strat, a, b) Calls the strategy
if/elif Stays in code without strategy

2 How does calculate(strategy, a, b) work in the Strategy pattern?

  • strategy(a, b) is called Correct answer
  • strategy is ignored
  • strategy is printed
  • strategy is deleted

Explanation: calculate calls the strategy parameter; it is a function.

3 Complete the calculate body

Question
def calculate(strategy, a, b):
    return ____(a, b)
Answer
def calculate(strategy, a, b):
    return strategy(a, b)

Explanation: return strategy(a, b) calls the strategy.

All lessons in Advanced