Advanced OOP and patterns · 3 / 15 Theory

Strategy and Factory patterns

A design pattern is a known solution to a recurring problem. In Python many of them are much shorter than in other languages, because functions and classes are ordinary objects.

Strategy: choosing the algorithm

If there are several ways of doing something (sorting, discounting, validating…), do not write a chain of if/elif: store the variants in a dictionary of functions and choose by name. Adding another does not force you to touch the code that uses them.

Factory: creating objects by name

A factory creates the right object from a piece of data (a name, a file type). With a registry and a decorator, each class registers itself.

# Strategy: the algorithm is chosen by passing a function
def sort_by(name, criteria, data):
    return sorted(data, key=criteria[name])

criteria = {
    "length": len,
    "alphabetical": str.lower,
    "reversed": lambda s: s[::-1],
}
words = ["Sun", "house", "arm", "Forest"]
print(sort_by("length", criteria, words))     # ['Sun', 'arm', 'house', 'Forest']
print(sort_by("alphabetical", criteria, words))   # ['arm', 'Forest', 'house', 'Sun']
print(sort_by("reversed", criteria, words))      # ['house', 'arm', 'Sun', 'Forest']

# Factory + registry: each class registers itself with a decorator
REGISTRY = {}

def fmt(name):
    def register(cls):
        REGISTRY[name] = cls
        return cls
    return register

@fmt("csv")
class Csv:
    def write(self, row):
        return ",".join(map(str, row))

@fmt("tsv")
class Tsv:
    def write(self, row):
        return "\t".join(map(str, row))

def create(name):
    return REGISTRY[name]()               # the factory does not know the concrete classes

print(create("csv").write([1, 2, 3]))     # 1,2,3
print(repr(create("tsv").write([1, 2])))  # '1\t2' 

You practice it in Discount strategies and Factory with a class registry.