• Python Snacks
  • Posts
  • Part 3: Mastering Object Oriented Programming: 3 OOP Design Patterns

Part 3: Mastering Object Oriented Programming: 3 OOP Design Patterns

In this multi-part series, I'm explaining the basics of object oriented programming (OOP) in Python.

This is part 2 of a 3 part series on object oriented programming. Below are all 3 parts of this series:

In this last part of this multi-part series, let’s explore some design patterns that you’ll often find in object oriented programming.

They help make code more modular, reusable, and readable, providing structure without reinventing the wheel.

What are design patterns?

Think of design patterns as templates for solving certain problems in code.

They don’t give you the exact code to copy-paste, but rather guide you in setting up classes, methods, and objects to solve specific types of problems in an organized way.

Each pattern has a unique purpose and works best in specific situations.

Pattern #1: Singleton Pattern

The singleton pattern ensures only one instance of a class exists and provides a way to access that instance globally.

It’s primarily useful when you need a single, consistent instance of an object across your application, like a database connection or logging service. For instance:

class Logger:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

# Every time we create a Logger, it returns the same instance
logger1 = Logger()
logger2 = Logger()
print(logger1 is logger2)  # True

Here, every time you create a Logger, you’re actually referencing the same object. This pattern is simple but crucial in cases where creating multiple instances could cause issues (like trying to open multiple connections to a single resource).

Pattern #2: Factory Pattern

The factory pattern helps create objects without specifying the exact class of object that will be created. Think of this as an assembly line for creating objects.

If you have a lot of classes that share a common interface but vary slightly in their specifics, a Factory can simplify the object creation process. For instance:

class PenFactory:
    def create_pen(self, pen_type):
        if pen_type == 'ballpoint':
            return BallPointPen()
        elif pen_type == 'gel':
            return GelPen()

# Instead of specifying the exact class, use the factory
factory = PenFactory()
my_pen = factory.create_pen('gel')

Here, the PenFactory handles the creation logic, so you don’t need to know the exact class when you request a pen. This keeps code flexible and makes it easier to add new pen types in the future.

3: Observer Pattern

The observer pattern allows objects to notify other objects about changes in its state.

You’ll want to use this when you have objects that need to automatically update in response to changes elsewhere. This pattern is common in event-driven programming and UI updates. For instance:

class NewsAgency:
    def __init__(self):
        self.subscribers = []

    def subscribe(self, subscriber):
        self.subscribers.append(subscriber)

    def notify(self, news):
        for subscriber in self.subscribers:
            subscriber.update(news)

class Subscriber:
    def update(self, news):
        print(f"News update: {news}")

agency = NewsAgency()
agency.subscribe(Subscriber())
agency.notify("Breaking news!")

When the NewsAgency has an update, it sends the news to all Subscribers. This way, each subscriber automatically gets the latest news without polling the agency.

Design patterns like Singleton, Factory, and Observer are just a few examples. They simplify your code by solving common structural challenges in predictable, reliable ways.

As you get comfortable with these patterns, you’ll start recognizing where they naturally fit in your projects, helping you write code that’s more modular, reusable, and easier to maintain.

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.