1. Home
  2. Explore
  3. Computer Science
  4. Design Patterns Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Design Patterns Overview

Design Patterns Course Notes

Introduction to Design Patterns

Design patterns are well-tested, reusable solutions to common software engineering problems. They function as solution templates, flexible and adaptable across a variety of scenarios. Having been used countless times, they are optimized and represent optimal solutions for recurring challenges.

Using design patterns provides several advantages:

  • Proven reliability – patterns have been successfully applied in many projects before.

  • Common meta-language for developers – understanding the same pattern (e.g., Singleton) creates a shared vocabulary, facilitating communication even across different programming languages.

  • Carry over between languages – the general concept of a pattern remains the same whether implemented in C++, Java, Dart, or Python, offering the same reusable solution.

Design patterns are associated with good, well-organized software design. They represent a bag of reusable experience from generations of coders and software engineers.


Design Patterns Covered in This Course

The course covers seven crucial design patterns, organized into three families:

Creational Patterns (managing object creation)

  1. Singleton – ensures a class has only one instance and provides global access to it.

  2. Factory Method – provides a mechanism for creating objects without exposing instantiation logic to the client.

  3. Builder – separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

Structural Patterns (managing object relationships)

  1. Adapter – converts the interface of a class into another interface that the client expects, enabling classes with incompatible interfaces to work together.

Behavioral Patterns (improving object communication)

  1. Strategy – defines a family of algorithms, encapsulates each one, and makes them interchangeable.

  2. Observer – creates a one-to-many dependency where when one object changes state, all its dependents are notified automatically.

  3. State – allows an object to alter its behavior when its internal state changes, appearing to change its class.

Each pattern is explained architecturally, then implemented in object-oriented Python, and finally applied in a simulation of John Conway's Game of Life.


Why Software Architecture Is Needed

Complex software systems face issues like stretched timelines, requirement changes, poor coordination among developers, code redundancy, and poor documentation. This leads to systems that are hard to maintain and not adaptable. Good design and architecture provide the blueprint, like the Empire State Building's high-level plan, ensuring predictability and coherence.

Development Cycle

  1. Requirements – gather and document UI, UX, and general project goals.

  2. Design – architect the system based on requirements (this course concentrates on this step).

  3. Implementation – code and test, ensuring the solution follows the design.

Design patterns are a key tool for achieving good architecture.


UML in This Course

UML is used to document design patterns because it communicates their structure very well in a highly visual representation. Two types of diagrams are used:

Class Diagrams

Convey the structure of a design pattern – classes, attributes, operations, and relationships (inheritance, aggregation, composition, dependency).

Sequence Diagrams

Illustrate interaction – how objects communicate and exchange messages over time.

UML Refresher – See separate section below for details on class and sequence diagram notation.


UML Refresher (Detailed)

Class Diagrams

Used to construct and visualize object-oriented relationships. Capture:

  • Class information: attributes and operations (methods).

  • Visibility: + (public), - (private) – not strictly used in Python but shows intent.

  • Relationships:

    • Generalization (inheritance) – an abstract class (e.g., Shape) has descendants (Triangle, Circle, Rectangle) that inherit from it.

    • Association (aggregation/composition) – e.g., a Cylinder is made up of shapes (aggregation). A white diamond indicates aggregation (part can exist without whole), a black diamond indicates composition (part cannot exist without whole).

    • Dependency – a class uses another class temporarily (e.g., Shape uses a Calculator). Shown with a dashed arrow.

Example: House UML

  • Interface IRO is implemented by abstract class Room.

  • Concrete rooms: Bathroom, LivingRoom, Bedroom inherit from Room.

  • House aggregates bathrooms (black diamond), living room, bedrooms, doors, windows, garage (black diamond), and pool (white diamond).

  • House depends on ElectricalGrid (dotted arrow).

Sequence Diagrams

Show behavior – message exchange over time. Capture:

  • Interaction information: actors, operations, method calls with data.

  • Lifelines: vertical dashed lines representing objects.

  • Arrows: method calls, return values.

  • Activation bars: when an object is active.


Python Object-Oriented Programming Refresher

Classes and Objects

A class is a recipe that provides:

  • Data container – variables/constants.

  • Operations on data – functions/methods.

An object is an instance of a class, holding specific data.
Example: class Greeting: with constructor __init__(self, name) and method say_hello().

In UML, simplify by showing class name, attributes, and methods without self.

Encapsulation

Gathers all relevant data and functionality in one place, controlling complexity.
Make sure to:

  • Create classes for all needed objects.

  • Build collections of related objects (e.g., Book aggregates Author).

Inheritance

Allows generalization: a child class inherits data and/or behavior from a parent class.
Example: Dog and Cat inherit from Animal and override the speak() method.
Key: child objects are still considered instances of the parent type.

Abstract Classes and Interfaces

  • Interface – a pure contract with no implementation (all methods abstract). In Python, implement using ABC and @abstractmethod.

  • Abstract class – partially implemented contract; some methods are abstract, others have default implementations. Used for reuse (e.g., Shape defines description() but leaves area() and perimeter() abstract).

Type hinting can enforce contracts: a function may require a parameter of a specific abstract type, guaranteeing certain methods exist.

Code Examples

  • Simple class: Greeting with name attribute.

  • Aggregation: Author inside Book – book contains author reference.

  • Inheritance with abstract: Animal (abstract sound(), concrete description()) → Dog, Cat.

  • Encapsulation: BankAccount with protected (_account_number) and private (__balance) attributes, getters/setters with preconditions.

  • Interface contract: MyInterface (abstract my_method) → MyClass and AnotherClass. A process_my_interface function accepts MyInterface objects and calls my_method() safely.

  • Abstract class with partial implementation: Shape (abstract area(), perimeter(), concrete description()) → Rectangle, Circle.


What Makes Great Architecture – Key Principles

Loose Coupling

Weak knowledge association between components. Changes to one component least affect others. Diagram: left (tight coupling, many connections), right (loose coupling, few connections).

Separation of Concerns

Break architecture into tiers: presentation layer (UI), business layer (logic), resource access layer (data access). Achieved through modularization, encapsulation, and arrangement in software layers.

Law of Demeter (LoD) – Principle of Least Knowledge

  • Each unit should have limited knowledge about other units.

  • Only talk to your immediate friends; do not talk to strangers.

  • Example: class A can talk to B, B can talk to C, but A should not talk directly to C.

SOLID Principles

  1. Single Responsibility Principle – a class should have only one reason to change.

  2. Open/Closed Principle – software entities should be open for extension but closed for modification.

  3. Liskov Substitution Principle – functions using base class references must be able to use objects of derived classes without knowing it.

  4. Interface Segregation Principle – clients should not be forced to depend upon interfaces they do not use (avoid fat interfaces).

  5. Dependency Inversion Principle – depend upon abstractions, not concretions.


Design Pattern: Singleton

Definition

Singleton is a creational design pattern that ensures a class has only one instance and provides an easy global access to that instance.

Main Tenets

  • Ensure only a single instance exists.

  • Provide easy global access to it.

  • Control instantiation – the class itself controls how it is created.

  • Critical regions must be entered serially – thread safety if multi-threaded.

Common Uses

  • Loggers – all logging goes to the same destination.

  • Caching – single cache for all clients.

  • Thread pools, database connections, configuration access.

Origin

One of the Gang of Four patterns. Motivation: "It is important for some classes to have exactly one instance. [...] There should be only one printer spooler, one file system, and one window manager."

When to Use / Not Use

  • Use when controlling access to a shared resource.

  • Avoid letting it degenerate into global access for everything, which hides dependencies and makes code harder to read. If it violates Single Responsibility Principle, reconsider.

Design Considerations

  • Lazy construction – create the instance only when first needed.

  • Eager loading – create immediately when the class is loaded (useful when instantiation must be fast).

  • Thread safety – protect critical sections with locks.

Implementation in Python

Classic Gang of Four Style

  • Override __init__ to raise an error (prevent external instantiation).

  • Provide a @classmethod get_instance() that lazily creates/stores the single instance.

  • Usage: s = Singleton.get_instance()

Simple Python Style (override __new__)

  • Override __new__ method to control object creation.

  • Check if class-level instance variable exists; if not, create and assign it; return the stored instance.

  • Allows normal constructor call (Singleton()).

Metaclass Approach (Best for Python)

  • Define a metaclass (subclass of type) that handles the singleton logic.

  • Override __call__ in the metaclass. When the class constructor is invoked, __call__ runs.

  • Maintain a dictionary _instances mapping class to instance.

  • Example:

    class SingletonMeta(type):
        _instances = {}
        def __call__(cls, *args, **kwargs):
            if cls not in cls._instances:
                cls._instances[cls] = super().__call__(*args, **kwargs)
            return cls._instances[cls]
  • The singleton class sets __metaclass__ = SingletonMeta (or use metaclass=SingletonMeta in Python 3).

  • This keeps the singleton logic separate from the business logic.

Eager Instantiation with Metaclass

  • Override __init__ (or __new__) in the metaclass to create the instance immediately when the class itself is loaded into memory.

  • Then in __call__, just return the already loaded instance.

  • Advantage: instance ready before any code asks for it.

Thread Safety

  • Add a lock (threading.Lock()) as a class-level variable.

  • When creating the instance, acquire the lock with with lock: to ensure only one thread creates it.

  • In the metaclass __call__ or __new__ method, protect the creation section.

Practical Example: Logger Singleton

Iterations refining the logger:

  1. Simple logger with file and console handlers.

  2. Encapsulate in a class, add get_instance() with lock for thread safety.

  3. Use metaclass singleton, return logger via get_logger().

  4. Final version: Use an abstract base logger class (with metaclass) and a concrete MyLogger that implements the abstraction. Clients use logger = MyLogger() and call methods like debug(), info() directly.


Design Pattern: Factory Method

Problem

Using constructors directly ties code to specific classes, violating the open/closed principle. Example: a space shooter game where different bullet types may be added later.

Definition

Factory Method is a creational design pattern that lets us abstract out the creation logic of specific class instances. It provides a mechanism for creation of objects without exposing the instantiation logic to the client.

Key Points

  • Objects are created by calling a factory method instead of a constructor.

  • Objects are created through an abstraction (interface/abstract class), not a concretion.

  • The caller only needs to know the factory method and an identifier (ID/type), not how the object is built.

Simple (Parameterized) Factory Method Variant

  • One static factory class with a create(type, ...) method.

  • Accepts a parameter (string, enum, etc.) and returns the appropriate concrete instance.

  • Hides the switch/conditional logic.

  • Preferred in most projects due to simplicity.

Classic (Gang of Four) Factory Method Variant

  • Each concrete product has a corresponding concrete factory class that implements a factory interface.

  • Client decides which factory to instantiate, then calls its creation method.

  • More classes but more extensible.

When to Use / Not Use

  • Use when the client cannot anticipate which concrete types it must create, or when new types may be added later.

  • No specific restrictions – it's generally beneficial for families of related objects.

Pros

  • Allows subclasses to choose object types.

  • Promotes loose coupling – client interacts only with the product interface.

  • Follows Single Responsibility Principle (creation logic in one place) and Open/Closed Principle (new product types can be added without modifying client code).

Cons

  • Can increase number of classes (parameterized factory avoids this).

Design Considerations

  • All product types should follow the same interface or abstract class.

  • Factory method returns the interface type.

  • Use a constant ID (enum or string) to specify which concrete type to create.

  • Optionally pass a context object to the factory for initialization data.

Code Example: Shape Factory

  • Abstract Shape with draw() method.

  • Concrete shapes: Circle, Rectangle.

  • ShapeFactory with create(shape_type, x, y) – returns a Shape.

  • Client requests shapes by type from factory.

  • Improved version: encapsulate parameters in a ShapeContext class.

  • Use Enum for shape types to avoid string constants.


Design Pattern: Builder

Problem

Complex objects (e.g., a house with many parts) often require long, unreadable constructors. The object itself is responsible for its creation, mixing representation and construction.

Definition

Builder is a creational design pattern that separates the construction of a complex object from its representation, so that the same construction process can create different representations.

Main Idea

  • Extract object construction into a separate Builder class.

  • The builder has methods for building each part (e.g., build_walls(), build_pool()).

  • A Director orchestrates the building process by calling builder methods in a specific sequence.

  • Different concrete builders produce different representations (e.g., WoodenHouseBuilder, StoneHouseBuilder).

Architecture (UML)

  • Product – the complex object to be built.

  • Builder (abstract) – declares methods for building parts and a get_result() method.

  • ConcreteBuilder – implements builder methods, returns a specific product.

  • Director – aggregates a builder, calls construct() which executes the steps.

  • Client: creates a concrete builder, passes it to the director, then retrieves the product.

Sequence Diagram

  1. Client creates a concrete builder.

  2. Client passes builder to director (via change_builder() or constructor).

  3. Client calls director's construct().

  4. Director calls builder's build methods in order.

  5. Director returns the product.

When to Use / Not Use

  • Use when a class has many optional parts, when you need to build different representations of the same product, or when constructing a complex composite tree.

  • Not needed for simple objects – use Factory Method instead.

Pros

  • Clear separation between construction and representation.

  • Finer control over construction steps.

  • Supports changing internal representation.

Cons

  • Increases number of classes.

  • Builder classes must be mutable.

Code Example: Pizza Builder

  • Pizza class with attributes: size, crust, sauce, toppings, price, name.

  • PizzaBuilder (abstract) – methods build_crust(), build_sauce(), build_toppings(), plus concrete helpers set_size(), add_notes().

  • Concrete builders: HawaiianPizzaBuilder, NewYorkPizzaBuilder. Each implements the three build methods with specific values.

  • PizzaDirector – takes a builder, calls make_pizza() which executes the three build steps, then returns the pizza.

  • Client: creates director, swaps builders, calls make_pizza() and get_pizza().


Design Pattern: Adapter

Problem

Existing classes or libraries have incompatible interfaces. E.g., investment data provider outputs XML, but charting library expects JSON. Or legacy rectangle uses Rectangle(x, y, w, h) but new code uses Rectangle(x1, y1, x2, y2).

Definition

Adapter is a structural design pattern that converts the interface of one class into another interface that the client expects. It lets classes work together that couldn't otherwise because of incompatible interfaces.

Two Forms of Conversion

  1. Data format adaptation – e.g., XML → JSON.

  2. Interface adaptation – e.g., different method signatures.

Architecture

  • Target – the interface that the client expects.

  • Adapter – implements the target interface, wraps the Adaptee.

  • Adaptee – the existing class with the incompatible interface.

  • The adapter translates the client's requests into calls to the adaptee, converting data or method parameters as needed.

Steps to Create an Adapter

  1. Identify the service (adaptee) you want to adapt.

  2. Declare the client interface (target) that defines how the client will communicate.

  3. Define the adapter class implementing the client interface.

  4. Add a private field to store reference to the adaptee.

  5. Implement each target method, delegating to the adaptee after performing necessary conversions.

  6. Ensure all clients use the adapter through the target interface.

When to Use / Not Use

  • Use when you want to reuse an existing class with an incompatible interface.

  • Avoid if performance is extremely time-sensitive (extra layer adds overhead).

Pros

  • Separates data conversion from business logic (Single Responsibility).

  • New adapters can be added without breaking client code (Open/Closed).

Cons

  • Increases code complexity with additional interfaces/classes.

Code Example: Contacts App with XML/JSON/CSV

  • Contact data class.

  • IXMLContactsReader, IJSONContactsReader provide raw data strings.

  • IContactAdapter (abstract) – method get_contacts() returns List<Contact>.

  • Concrete adapters: XMLContactAdapter (wraps XMLContactsReader), JSONContactAdapter (wraps JSONContactsReader). Each adapter parses raw data into Contact objects.

  • Client uses adapter interface to fetch contacts, unaware of the underlying format.


Design Pattern: Strategy

Problem

A class (e.g., web scraper) has multiple conditional branches for different algorithms (e.g., parsing XML, SQL, CSV). The code becomes bloated, hard to maintain, and violates Open/Closed principle.

Definition

Strategy is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.

Architecture

  • Context – the class that uses a strategy. It aggregates a Strategy interface.

  • Strategy – declares an interface common to all supported algorithms (e.g., execute(data)).

  • ConcreteStrategy – implements the algorithm.

  • Client chooses which concrete strategy to use and injects it into the context, often via a setter or constructor.

When to Use / Not Use

  • Use when you have multiple variants of the same algorithm and need to switch between them at runtime.

  • Avoid if the number of algorithms is small and rarely changes – the added complexity may not be justified.

Pros

  • Follows Open/Closed Principle – new strategies can be added without modifying context.

  • Promotes Single Responsibility – each strategy handles its own algorithm.

  • Allows runtime switching.

Cons

  • Clients must be aware of the differences between strategies to select the appropriate one.

Code Example: Renderers in Flutter

  • Renderer (abstract) – method render() returns a Widget.

  • Concrete strategies: ImageRenderer, ButtonRenderer, WidgetRenderer.

  • MainPageState (context) holds a Renderer object.

  • Radio buttons change the renderer strategy.

  • The build method simply calls _renderer.render() – no conditional logic.


Design Pattern: Observer

Problem

One object (subject) has state changes that need to be communicated to many other objects (observers) without tightly coupling them.

Definition

Observer is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Key Concepts

  • Subject (Publisher) – maintains a list of observers. Provides attach(), detach(), and notify().

  • Observer – interface with a single update() method.

  • When the subject's state changes, it iterates over all observers and calls their update() method.

  • Observers can then query the subject for the new state (pull model) or receive the state in the update call (push model).

Architecture UML

  • Subject – state, attach(Observer), detach(Observer), notify().

  • Observer – update().

  • ConcreteObserver – implements update() and accesses the subject's state.

When to Use / Not Use

  • Use when changes to one object need to be known by other objects, especially when the set of observers is dynamic.

  • Avoid if the order of notifications is critical (notifications are typically unordered).

Pros

  • Loose coupling between subject and observers.

  • Dynamic relationships – can add/remove observers at runtime.

  • Enables reactive behavior.

Cons

  • Notification order is random.

  • Debugging may be difficult due to many notifications.

Implementation in Flutter using Streams

  • StreamController – used to broadcast events.

  • For multiple listeners, use StreamController.broadcast().

  • Producers push data into the stream sink.

  • Consumers listen via StreamBuilder (for widgets) or StreamSubscription (for code).

  • Example: Counter app with increment/decrement buttons. Button presses send events via event stream; controller listens to event stream, updates counter, and pushes new counter value via counter stream; UI listens via StreamBuilder and updates text.


Design Pattern: State

Problem

An object's behavior depends on its internal state, and the number of states is non-trivial. Using many conditionals (if/else, switch) makes code hard to maintain.

Definition

State is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Finite State Machine (FSM) Concept

  • States – finite set of possible modes.

  • Actions – events that trigger transitions.

  • Transitions – moving from one state to another.

  • Example: Toaster states: Idle, BreadLoaded, Toasting, BreadEjected. Actions: insert bread, pull lever, eject, finish toasting.

Architecture

  • Context – the object whose behavior varies with state. It has a reference to a State object.

  • State (abstract) – declares the interface that all concrete states must implement.

  • ConcreteState – implements behavior specific to that state and defines transitions (by calling context's setter with another state object).

  • Transitions are handled within the states themselves – each concrete state knows what the next state should be.

Sequence Diagram

  • Client calls context.action() (e.g., switch()).

  • Context delegates to current state's method.

  • The state method performs the action and may create a new state, setting it in the context.

  • Next call to context uses the new state.

When to Use / Not Use

  • Use when an object's behavior depends on its state and there are many stateful conditionals.

  • Avoid if states are simple and transitions rare – pattern may introduce unnecessary complexity.

Pros

  • Removes bulky conditionals.

  • Follows Open/Closed Principle – new states can be added without changing existing ones.

  • Follows Single Responsibility Principle – each state class handles its own logic.

Cons

  • Number of classes can grow with many states.

Code Example: Traffic Light

  • States: GreenState, YellowState, RedState (each implements TrafficLightState with next_color() and get_color()).

  • TrafficLight (context) holds current state, initialized to GreenState.

  • next() method in context calls current_state.next_color(this), which sets the next state (e.g., Green.next sets YellowState).

  • UI uses a timer to call traffic_light.next() every 3 seconds.

  • Transition logic is hidden inside the states – no big switch statements.


Course Assignment: Game of Life

What is the Game of Life?

  • A cellular automaton invented by John Conway in 1970.

  • Zero-player game – evolution is determined by initial state.

  • Universe is an infinite two-dimensional orthogonal grid of cells.

  • Each cell is alive or dead.

  • At each time step (tick), the next generation is computed based on three rules:

Rules

  1. Survival: Any live cell with two or three live neighbors survives to the next generation.

  2. Birth: Any dead cell with exactly three live neighbors becomes a live cell.

  3. Death: All other live cells die (by loneliness or overpopulation); all other dead cells stay dead.

Architecture Task

  • Design, architect, and develop a version of the game using all the design patterns learned.

  • Steps:

    1. Write down requirements (what input/output, user interaction).

    2. Create high-level diagram of main objects (grid, renderer, timer, generation logic).

    3. Expand into specific classes and identify where design patterns fit (e.g., Observer for timer ticks, Strategy for rendering, Singleton for configuration, Factory for cell creation, etc.).

    4. Write code, document, test.

Hints

  • Build a proof of concept first with minimal UI (e.g., console output).

  • Start with a small grid (10x10 or 16x16).

  • Use a timer (observer pattern) to trigger ticks at regular intervals.

  • Abstract the UI layer (use Strategy pattern for different renderers).

  • Consider pause/resume, save/load functionality.

  • Use provided starter code and refactor it using patterns.


Conclusion

This course covered the seven most fundamental design patterns in software engineering: Singleton, Factory Method, Builder, Adapter, Strategy, Observer, and State. Understanding and applying these patterns gives you a reusable vocabulary and experience from generations of developers. Practice is essential – try to recognize and use these patterns in your own projects, always guided by SOLID principles and good architectural practices (loose coupling, separation of concerns, Law of Demeter).

Continue exploring more patterns and advanced topics like architectural patterns (microservices, event bus), thread safety (producer-consumer), and state management in mobile applications. Keep coding!

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent