Over the three previous lessons, Íker has solved several problems in Verdalia's code by applying principles. Some of his solutions, such as creating one class per shipping method or putting an interface of his own in front of PagoRaíz, look very much like the ones thousands of teams have found when facing similar problems. Those recurring solutions have names: they are design patterns. In this lesson you will learn what they are, how they are classified, and how six of the most widely used ones are applied. You will also learn when not to use them, which is just as important.
What a Design Pattern Is
A design pattern is a proven, named solution to a design problem that appears repeatedly in a given context. It is not a piece of code to copy, but an idea that is adapted to each case.
Every pattern is described with four elements:
| Element | What it answers | Example with the Adapter pattern |
|---|---|---|
| Problem | What difficulty does it solve? | I need to use a component whose interface does not match the one my code expects |
| Context | In which situations does it appear? | When integrating libraries or external services I cannot modify |
| Solution | What structure is proposed? | An intermediate class that offers my interface and translates the calls |
| Consequences | What is gained and what is paid? | I isolate the external component, at the cost of one more class |
The fourth element is what distinguishes a mature use of patterns: they all have a cost, and they are part of the trade-offs we studied in Module 1.
The idea comes from building architecture. In the 1970s, the architect Christopher Alexander cataloged recurring solutions in the design of houses and towns. In 1994, four authors, Gamma, Helm, Johnson, and Vlissides, brought the idea to software in a book that described 23 patterns and became the classic reference.
Patterns contribute two things. The first is accumulated experience: the solution does not have to be reinvented. The second, often more valuable, is vocabulary. When Marta says “let's put an adapter in front of PagoRaíz,” the team understands in one sentence what would otherwise need a long explanation.
Classification of Patterns
The classic patterns are grouped into three families according to their purpose:
| Family | What it deals with | Most used patterns |
|---|---|---|
| Creational | How objects are created | Factory Method, Abstract Factory, Builder, Singleton |
| Structural | How classes and objects are composed to form larger structures | Adapter, Decorator, Facade, Proxy, Composite |
| Behavioral | How responsibilities are distributed and how objects communicate | Strategy, Observer, Command, Template Method, State |
In this lesson we develop six, two from each family. We use their standard names because they are the ones you will find in documentation and in any team's conversations.
| Pattern | Family | In one sentence | Use at Verdalia |
|---|---|---|---|
| Factory Method | Creational | A single point decides which concrete class is created | Getting the shipping method from its code |
| Singleton | Creational | Guarantees a single, globally accessible instance | The store's configuration |
| Adapter | Structural | Converts one interface into another | The PagoRaíz library |
| Decorator | Structural | Wraps an object to add behavior to it | Retries and logging of charges |
| Strategy | Behavioral | Encapsulates interchangeable algorithms | Shipping rates and discounts |
| Observer | Behavioral | Notifies interested parties when something happens | Reactions to “order confirmed” |
Factory Method: Creating Without Knowing the Concrete Class
Problem. The order stores the shipping method as a string: "standard" or "express". The code that uses it needs the corresponding object, but it should not know which classes exist. If it did, every new method would force a modification.
Solution. Concentrate creation at a single point, the factory, which receives the code and returns an object that fulfills the ShippingMethod interface.
# verdalia/shipping/factory.py
from verdalia.shipping.methods import StandardShipping, ExpressShipping
_CLASSES = {cls.code: cls for cls in (StandardShipping, ExpressShipping)}
def create_shipping_method(code):
"""Returns the shipping method that corresponds to a code."""
if code not in _CLASSES:
raise ValueError(f"Unknown shipping method: {code}")
return _CLASSES[code]()
def calculate_shipping_cost(amount, method="standard"):
return create_shipping_method(method).calculate_cost(amount)
method = create_shipping_method("express")
print(type(method).__name__, method.calculate_cost(45.0))Output:
Explanation:
_CLASSESis a dictionary that maps each code to its class. It is built from a list of classes, reading thecodeattribute of each one.create_shipping_methodlooks up the class and creates an object with_CLASSES[code](). The caller receives aShippingMethodand never mentions a concrete class.calculate_shipping_cost, the module's public function, now relies on the factory. It replaces theMETHODSlist we used in the lesson on SOLID.
In its classic form, the pattern is built with a creator class that declares a creation method, and with subclasses that override it to decide which object is created. In Python a function and a dictionary are usually enough, as here. The idea is the same: separate the decision of what to create from the code that uses what was created.
Consequences. The list of available methods lives in a single place. In exchange, there is one more indirection: to know which class is in use you have to look at the factory.
Singleton: A Single Instance
Problem. Some objects must be unique across the whole application, such as the configuration.
Solution. The class itself controls its creation and always returns the same instance.
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.test_mode = False
return cls._instance
a = Config()
b = Config()
b.test_mode = True
print(a is b, a.test_mode)Output:
Explanation:
__new__is the method Python runs to create an object. Here it only creates one the first time; afterward it returns the one it stored in_instance.aandbare the same object. That is why changingb.test_modealso changesa.test_mode.
Why It Is Controversial
The example's output shows the problem: a change made at one point in the program alters what everyone else sees. A Singleton is, in practice, a global variable with a nicer look.
| Drawback | Consequence |
|---|---|
| Global state | It is the common coupling we saw in the first lesson of the module |
| Hidden dependencies | A class's constructor does not reveal that it uses the configuration |
| Tests that contaminate one another | What one test modifies, the next one inherits |
| False guarantee | The store runs in 4 worker processes, and each one has its own “single” instance |
The Alternative
That a single instance exists is a decision for whoever assembles the application, not for the class. It is enough to create the object once, at startup, and hand it to whoever needs it:
# verdalia/app.py
config = load_config() # created only once
client = PagoRaizClient(config.pagoraiz_key)Config goes back to being an ordinary class, and each component declares in its constructor what it needs. This technique is called dependency injection, and we will develop it in the next lesson. Verdalia adopts this alternative and gradually replaces the global variable connection, which was a de facto Singleton.
Adapter: Translating a Foreign Interface
Problem. PagoRaíz has published an official Python library. The team wants to use it instead of building the HTTP requests by hand, but the library has its own vocabulary: it works in cents, requires the currency, and returns a dictionary.
Solution. An adapter class that offers the store's interface, PaymentGateway, and translates each call into the library's language.
class PagoRaizClient:
"""Simulation of the official library, so the example can run."""
def __init__(self, key):
self._key = key
def create_charge(self, amount_cents, currency, description):
return {"status": "AUTHORIZED", "charge_id": "PR-778201"}
# verdalia/payments/pagoraiz_gateway.py
class PagoRaizGateway(PaymentGateway):
"""Adapter: offers Verdalia's interface and speaks PagoRaiz's language."""
def __init__(self, client):
self._client = client
def charge(self, reference, amount):
response = self._client.create_charge(
amount_cents=round(amount * 100),
currency="EUR",
description=reference,
)
return ChargeResult(
accepted=response["status"] == "AUTHORIZED",
transaction_id=response["charge_id"],
)
gateway = PagoRaizGateway(PagoRaizClient(key="example-key"))
print(gateway.charge("ORD-1042", 49.95))Output:
Explanation:
PagoRaizClientrepresents the external library. We cannot change it: it belongs to PagoRaíz.PagoRaizGatewayinherits fromPaymentGateway, the interface we defined when studying dependency inversion. It receives the client in its constructor.chargetranslates in both directions. On the way out, it converts euros into cents and adds the currency. On the way back, it converts the dictionary into aChargeResult.- Notice what has not changed:
OrderService. The way of talking to PagoRaíz has been replaced and the orders module has not noticed.
Consequences. PagoRaíz's vocabulary is locked inside a single class. If the library changes, or if one day the gateway is switched, only the adapter is modified or replaced. The cost is an additional class that has to be kept up to date.
Decorator: Adding Behavior Without Modifying
Problem. Lucía asks for two improvements: that every charge be logged and that, if PagoRaíz does not respond, the call be retried before the payment is declared failed. Writing all that inside the adapter would mix three responsibilities.
Solution. Wrap the object in another one that fulfills the same interface, adds its behavior, and delegates the rest. Wrappers can be stacked.
class GatewayConnectionError(Exception):
"""The gateway did not respond."""
class RetryingGateway(PaymentGateway):
def __init__(self, gateway, max_attempts=3):
self._gateway = gateway
self._max_attempts = max_attempts
def charge(self, reference, amount):
for attempt in range(1, self._max_attempts + 1):
try:
return self._gateway.charge(reference, amount)
except GatewayConnectionError:
print(f"[Retries] Attempt {attempt} failed")
if attempt == self._max_attempts:
raise
class LoggingGateway(PaymentGateway):
def __init__(self, gateway):
self._gateway = gateway
def charge(self, reference, amount):
print(f"[Log] Charge requested: {reference}, €{amount:.2f}")
result = self._gateway.charge(reference, amount)
print(f"[Log] Result: accepted={result.accepted}")
return result
gateway = LoggingGateway(RetryingGateway(FlakyGateway()))
gateway.charge("ORD-1043", 24.75)For the example, FlakyGateway was used, a simulated gateway that fails the first two times and accepts the third. Output:
[Log] Charge requested: ORD-1043, €24.75 [Retries] Attempt 1 failed [Retries] Attempt 2 failed [Log] Result: accepted=True
Explanation:
- Each decorator is a
PaymentGatewaythat contains anotherPaymentGateway. Whoever uses it cannot tell whether it is facing the real gateway or a wrapped one. RetryingGatewayrepeats the call when there is a connection error. Once the attempts are exhausted, it re-raises the error withraise.LoggingGatewayrecords the request and the result. In the real store it will write to the application log instead of usingprint.- The last line stacks the pieces: logging on the outside, retries in the middle, and the gateway inside. It is composition over inheritance in its purest form.
An important warning: retrying a charge is delicate, because it can charge twice. That is why it is only retried when the connection fails, never when the payment is declined, and always with the same reference, so the gateway can recognize the repetition. We will come back to this problem in Module 3, when studying communication between components.
A note about Python: the language has a syntax called decorator, the one written with @, such as @dataclass. It shares the idea of wrapping, but it applies to functions and classes at the moment they are defined. The pattern wraps objects while the program runs.
Consequences. Each behavior lives in its own class and combines freely. In exchange, with many layers it becomes harder to follow a call, and the order in which they are stacked matters.
Strategy: Interchangeable Algorithms
Problem. The same operation admits several algorithms, and it must be possible to choose one or another without filling the code with conditions.
Solution. Define an interface for the algorithm and one class per variant. The code that uses it receives the variant from outside.
You already know this pattern: ShippingMethod, with StandardShipping and ExpressShipping, is a strategy for calculating shipping costs. Let's apply it to another real case, campaign discounts, such as the 15% on the day before Mother's Day:
class DiscountPolicy(ABC):
@abstractmethod
def apply(self, amount):
"""Returns the amount once the discount has been applied."""
class NoDiscount(DiscountPolicy):
def apply(self, amount):
return amount
class PercentageDiscount(DiscountPolicy):
def __init__(self, percentage):
self._percentage = percentage
def apply(self, amount):
return round(amount * (1 - self._percentage / 100), 2)
def amount_to_charge(amount, policy):
return policy.apply(amount)
print(amount_to_charge(45.0, NoDiscount()))
print(amount_to_charge(45.0, PercentageDiscount(15)))Output:
Explanation:
DiscountPolicyis the strategy's interface, and each subclass is a variant.NoDiscountavoids treating the absence of a discount as a special case: the code always has a policy, even if it does nothing.amount_to_chargecontains no condition. The behavior changes depending on the object it receives.
In Python, a simple strategy can be just a function passed as a parameter. Classes pay off when the variant needs data of its own, such as the percentage, or several methods.
Strategy and Factory Method complement each other: the strategy defines the interchangeable variants and the factory decides which one is created in each case.
Consequences. Adding a variant does not modify the existing ones, which is the open-closed principle. In exchange, the number of classes grows, and whoever configures the system has to know the available variants.
Observer: Reacting to What Happens
Problem. When an order is confirmed, other areas have to react: inventory deducts the stock and notifications tells the warehouse to prepare the package. In the monolith, confirm_order called each one directly. Every new reaction forced a modification of the orders code, and orders depended on everyone.
Solution. The emitter announces that something has happened, without knowing who is listening. Interested parties subscribe beforehand.
flowchart LR
service["OrderService"] -->|"publishes order_confirmed"| publisher["EventPublisher"]
publisher --> inventory["Inventory - deduct stock"]
publisher --> notifications["Notifications - notify the warehouse"]
class EventPublisher:
def __init__(self):
self._subscribers = {}
def subscribe(self, event_type, handler):
self._subscribers.setdefault(event_type, []).append(handler)
def publish(self, event_type, data):
for handler in self._subscribers.get(event_type, []):
handler(data)
# Inventory module
def deduct_stock(order):
print(f"[Inventory] Stock deducted for order {order.id}")
# Notifications module
def notify_warehouse(order):
print(f"[Notifications] Warehouse alert: prepare order {order.id}")
publisher = EventPublisher()
publisher.subscribe("order_confirmed", deduct_stock)
publisher.subscribe("order_confirmed", notify_warehouse)
order = Order(id=1042, customer_email="[email protected]", amount=45.0)
publisher.publish("order_confirmed", order)Output:
Explanation:
_subscribersis a dictionary that maps each event type to the list of functions that must run.setdefaultcreates the list the first time.subscribeadds a function to the list.publishgoes through the list and calls each function with the event's data.- Subscriptions are made when the application starts. In
OrderService.confirm, one line at the end is enough:publisher.publish("order_confirmed", order). - If Andrés asks to record every sale in some statistics, the function is written and subscribed. The orders module is not modified.
What Goes Through the Publisher and What Doesn't
The team applied a criterion: the steps that are part of the operation itself remain explicit calls, and the consequences that interest other areas go through the publisher.
| Step | How it is resolved | Reason |
|---|---|---|
| Charging | Explicit call | If there is no charge, there is no confirmed order |
| Confirmation email to the customer | Explicit call | It is part of what the customer understands by confirming |
| Deducting stock | Subscriber | Consequence that interests inventory |
| Notifying the warehouse | Subscriber | Consequence that interests shipment preparation |
It is a debatable decision, and we will revisit it in Module 3.
Consequences. The emitter is decoupled from those who react, and adding reactions is cheap. In exchange:
- The complete flow can no longer be seen in one place: to know what happens when an order is confirmed, you have to look up the subscriptions.
- Everything still happens inside the same process and synchronously. The customer waits until the last subscriber finishes.
- If a subscriber fails, the error reaches the emitter and the following subscribers do not run.
The last two limitations are solved by taking the events out of the process with message queues. That is the distributed version of the same pattern, which we will study in Module 3.
When Not to Use Patterns, and Frequent Antipatterns
Overengineering
A pattern solves a problem. If the problem does not exist, the pattern only contributes classes, files, and indirection. Using them systematically is a way of violating the KISS and YAGNI principles from the previous lesson.
| Sign | What it indicates |
|---|---|
| A factory that creates only one class | There is no decision to encapsulate |
| A strategy with a single variant | A function is enough |
| A publisher with a single subscriber that never changes | A direct call is clearer |
Names like AbstractManagerFactory |
The design describes the pattern, not the business |
| Nobody can explain what problem it solves | The pattern was chosen before the problem |
The practical rule is to arrive at patterns by refactoring: first the pain appears, and then the pattern that relieves it is applied. That is what happened with the shipping methods. The opposite, starting from the pattern, usually ends badly.
Antipatterns
An antipattern is a common solution that looks reasonable and causes more problems than it solves. They have names too:
| Antipattern | What it consists of | Example |
|---|---|---|
| God object | A class that knows and does too much | OrderManager, with 1,400 lines |
| Spaghetti code | Tangled flow, with no recognizable structure | Functions that call one another in a circle |
| Copy-and-paste programming | Duplicating instead of reusing | The three copies of the shipping costs |
| Golden hammer | Using the favorite tool for everything | Solving every problem with a Singleton or a publisher |
| Lava flow | Dead code nobody dares to delete | Functions in utils.py that nobody uses anymore |
Design Pattern vs. Architectural Pattern
The patterns in this lesson and the architectural styles from Module 1 are named solutions, but they act at different scales:
| Aspect | Design pattern | Architectural pattern or style |
|---|---|---|
| Scale | A few classes or objects | The system or a complete component |
| What it organizes | The code inside a module | The modules, the processes, and their deployment |
| Cost of reverting it | Hours or days | Weeks or months |
| Quality attributes | Mainly maintainability | All of them: availability, scalability, security |
| Examples | Strategy, Adapter, Observer | Layers, microservices, event-driven |
| Recorded in an ADR | Usually not | Yes |
Many ideas appear at both scales. The Observer pattern, taken outside the process, is event-driven architecture. And the Adapter pattern, applied systematically to everything surrounding the business logic, gives rise to a complete architecture, which is the subject of the next lesson.
Common Mistakes and Tips
- Collecting patterns. The goal is not to use many, but to solve problems. Code without a single recognizable pattern can be excellent.
- Applying the pattern to the letter. The classic catalogs were written with other languages in mind. In Python, a function or a dictionary is often enough.
- Using Singleton to avoid passing parameters. It hides dependencies instead of resolving them.
- Writing adapters that leak details. If
chargereturned PagoRaíz's dictionary, the rest of the store would still be tied to its format. - Retrying operations without thinking about their effects. Repeating a query is harmless; repeating a charge is not.
- Using Observer when the result is needed. If the emitter needs to know what happened, it is not an event, it is a call.
- Practical tip. Before applying a pattern, write in one sentence the problem it solves in your code. If you cannot, you do not need it.
Exercises
Exercise 1: Choose the Pattern
State which pattern you would apply in each situation, or whether you would apply none:
- The external email service offers a library whose method is
send_message(to, subject, html, tags), and the store uses theNotifierinterface. - You want to keep the results of catalog searches in memory for five minutes, without modifying the class that performs them.
- Depending on the type of customer, the price is calculated with the regular rate or with the rate for gardening professionals.
- The store issues a single type of invoice, and a colleague proposes creating an invoice factory.
Exercise 2: A Decorator for Timing
Lucía wants to know how long each charge takes. Write a TimingGateway decorator that measures the duration of each call and prints it in milliseconds. Use time.perf_counter(), which returns an instant in seconds.
Solutions
Solution to Exercise 1
- Adapter. A class that implements
Notifierand translates the call intosend_message. - Decorator. A class with the same interface that wraps the original, stores the results, and returns them without repeating the search.
- Strategy. Two variants of the same calculation, chosen according to the customer.
- None. With a single type there is no decision to encapsulate. If one day a second type of invoice appears, it will be introduced then.
Solution to Exercise 2
import time
class TimingGateway(PaymentGateway):
def __init__(self, gateway):
self._gateway = gateway
def charge(self, reference, amount):
start = time.perf_counter()
try:
return self._gateway.charge(reference, amount)
finally:
milliseconds = (time.perf_counter() - start) * 1000
print(f"[Timer] {reference}: {milliseconds:.0f} ms")
gateway = TimingGateway(SlowGateway())
print(gateway.charge("ORD-1044", 63.0))Output, with a simulated gateway that takes a quarter of a second. The exact value varies on each run:
The try block with finally guarantees that the duration is printed even when the charge raises an error, which is precisely when it is most interesting to know. The decorator does not know whether it wraps the real gateway, the retrying one, or a simulated one.
Common mistake: measuring the time inside PagoRaizGateway. It works, but it mixes responsibilities and is useless for other gateways.
Conclusion
In this lesson you have learned that a design pattern is a named solution to a recurring problem, described by its problem, its context, its solution, and its consequences. You have seen the three classic families and six patterns applied to the store: a factory that hands over the shipping method, a Singleton and the alternative that avoids it, an adapter for the PagoRaíz library, decorators to retry and log charges, strategies for discounts, and a publisher that notifies inventory and notifications when an order is confirmed. You have also seen that a pattern without a problem is overengineering, and that design patterns and architectural patterns share ideas at different scales.
Verdalia now has well-designed pieces, but each one has been built separately. What is missing is an overall rule that says where everything goes and who may depend on whom. Also missing is something the team has not had in six years: automated tests. Both arrive together in the last lesson of the module: “From Principles to Architecture: Dependency Inversion, Ports and Adapters.”
