Creational & Structural Patterns

Creational & Structural Patterns in Python: Imagine you are building a house. You don't start by guessing where the walls should go.

Concept Explanation

Imagine you are building a house. You don't start by guessing where the walls should go. You use a Blueprint that has been tested by thousands of architects before you.

Design Patterns are those blueprints for software. They are proven solutions to common problems. If you find yourself thinking, "How should I structure this system so it doesn't break later?", there is likely a design pattern that gives you the answer. In Python, these patterns are often simpler to implement because of the language's flexibility.


Syntax or Core Structure

The Singleton Pattern

Goal: Ensure a class has only ONE instance (like a Database Connection or a Settings object).

class DatabaseConnection:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            # Create the object only if it doesn't exist
            cls._instance = super().__new__(cls)
            print("Connecting to Database...")
        return cls._instance

# Both variables point to the exact same object
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(db1 is db2) # True

Code Example #1 (Basic)

The Factory Pattern: Creating objects without specifying the exact class.

class Dog:
    def speak(self): return "Woof!"

class Cat:
    def speak(self): return "Meow!"

def pet_factory(pet_type):
    # The factory decides which object to build
    pets = {"dog": Dog(), "cat": Cat()}
    return pets.get(pet_type, Dog())

job = pet_factory("cat")
print(job.speak()) # "Meow!"

Code Example #2 (Intermediate)

The Observer Pattern: One object "notifies" many others when something changes (useful for Chat apps or Stock tickers).

class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def notify(self, message):
        for observer in self._observers:
            observer.update(message)

class User:
    def __init__(self, name): self.name = name
    def update(self, msg): print(f"{self.name} received: {msg}")

# Setup
news_agency = Subject()
user_a = User("Alice")
news_agency.attach(user_a)

news_agency.notify("Breaking News!") # Alice receives it!

Real World Example

Logger System: Using a Singleton for a logger ensures that every part of your app writes to the same log file without opening it 100 times. Using a Strategy Pattern for the logger would allow you to switch from "Save to File" to "Send to Email" instantly by just swapping one class.


Common Mistakes

  1. Over-Engineering: Using a Design Pattern for a tiny script. If your code is only 50 lines long, a Singleton is just extra typing. Patterns are for Scalability.
  2. Strictness: Some developers try to force Python to look like Java when using patterns. Don't! Use Pythonic features like decorators or modules (a Python module is already a Singleton by default!).
  3. Pattern Gravy: Mixing 5 different patterns into one function. Keep it simple.

Best Practices

  • Use the Right Tool: Use a Factory when you have many similar things (like different types of weapons in a game). Use an Observer when you have one "Brain" and many "Listeners".
  • Composition over Inheritance: Instead of making one giant class that does everything, give your class "Components" that handle specific tasks.
  • Don't Reinvent the Wheel: Most patterns are already available in Python libraries. For example, the Observer pattern is the core of libraries like rxpy or Django Signals.

Practice Exercises

  1. The Shape Factory: Create a factory function that returns either a Square, Circle, or Triangle object based on a string input.
  2. The Logger: Implement a Singleton Logger class that has a log() method. Demonstrate that calling it from different files uses the same instance.
  3. The Notifier: Build a simple "Newsletter" system where users can "Subscribe" and receive an email (print statement) whenever a new article is posted.