Command Pattern in Python
This story is part of the “Design Patterns” series. You can find the other stories of this series here:
You can also find all the code used through this series on GitHub.
The Command pattern is a design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.
This allows for decoupling of objects that invoke operations from the objects that perform those operations.
Problems the Command Pattern can Solve
Imagine we’re building a program that simulates a vending machine. The program might have a single function called dispense
that is responsible for dispensing a product from the vending machine. This function would take in the product code, check the inventory, and dispense the product if it is available.
class VendingMachine:
def __init__(self):
self.inventory = {"cola": 5, "water": 10, "juice": 8}
def dispense(self, product_code):
if product_code not in self.inventory…