Mastering Python Logic: Template Method and Bridge Patterns

Overview

Software developers often struggle with classes that grow too large and carry too many responsibilities. This tutorial explores how to refactor a messy trading bot into a clean, modular system by using two underrated design patterns: the

and the
Bridge Pattern
. By the end, you will understand how to standardize a high-level process while allowing specific steps and external dependencies to vary independently.

Prerequisites

To follow this tutorial, you should have a solid grasp of

basics, including classes and inheritance. Familiarity with
Object-Oriented Programming
(OOP) and the concept of
Abstract Base Classes
is essential, as these serve as the backbone for both design patterns.

Key Libraries & Tools

  • abc (Abstract Base Classes): A built-in
    Python
    module used to define blueprints for other classes, ensuring subclasses implement specific methods.
  • Trading Bot Example: A practical context involving cryptocurrency exchanges like
    Binance
    and
    Coinbase
    to demonstrate real-world decoupling.

The Template Method Walkthrough

The Template Method defines the skeleton of an algorithm in a base class but lets subclasses override specific steps without changing the overall structure. We start by defining a TradingBot that outlines the check_prices process.

Mastering Python Logic: Template Method and Bridge Patterns
Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
from abc import ABC, abstractmethod

class TradingBot(ABC):
    def check_prices(self, coin):
        self.exchange.connect()
        prices = self.exchange.get_market_data(coin)
        if self.should_buy(prices):
            print(f"Buying {coin}")
        if self.should_sell(prices):
            print(f"Selling {coin}")

    @abstractmethod
    def should_buy(self, prices):
        pass

    @abstractmethod
    def should_sell(self, prices):
        pass

By making should_buy and should_sell abstract, we force specific implementations like an AverageTrader or MinMaxTrader to define their own logic while keeping the execution flow identical.

Bridging Independent Variations

While the Template Method handles internal logic steps, the

decouples an abstraction from its implementation so the two can vary independently. In our bot, the "Exchange" (where data comes from) is a separate concern from the "Trader" (how we decide to trade).

class Exchange(ABC):
    @abstractmethod
    def connect(self):
        pass

class BinanceExchange(Exchange):
    def connect(self):
        print("Connecting to Binance...")

We pass an Exchange instance into the TradingBot. This allows us to swap

for
Coinbase
without touching a single line of our trading strategy logic.

Tips & Gotchas

Always prioritize cohesion. A class should do one thing well. Avoid the temptation to use these patterns for very simple scripts where a basic function suffices; over-engineering adds unnecessary boilerplate. When debugging, remember that you cannot instantiate abstract classes directly—

will throw an error if you forget to implement even one abstract method in your subclass.

Mastering Python Logic: Template Method and Bridge Patterns

Fancy watching it?

Watch the full video and context

3 min read