Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Quick MCQ — Factory purpose

  • A) Factory centralizes object creation to avoid scattered new/constructors

  • B) Factory enforces inheritance hierarchies for behavior

  • C) Factory broadcasts events to many listeners

Correct: A — Factory centralizes object creation.


Additional Exercises

  1. Extend ExporterFactory to return a JSONExporter and test it.

  2. Refactor ExporterFactory.get_exporter to use a registration dict instead of if/else chains.

  3. Write a short note (markdown cell) about when a factory is too much indirection and simple constructors are better.


Introduction to Design Patterns

Reusable software blueprints for business systems, APIs, dashboards, and ML-ready applications.

Design patterns are not about writing more code. They are about writing code that stays understandable when requirements, teammates, and business rules start changing every week.


Why This Chapter Matters

When a project grows, the hardest part is usually not syntax. The hard part is deciding:

  • where object creation should happen

  • how behavior should change without giant if/else blocks

  • how one change should notify the rest of the system

  • how to extend behavior without rewriting stable code

Patterns give you names for these recurring design choices.

A pattern is a proven way to organize responsibility, not a magic spell.


Pattern Families at a Glance

FamilyCore questionExample in this book
CreationalHow should objects be created?Factory
BehavioralHow should objects collaborate and switch behavior?Strategy, Observer
StructuralHow should functionality be layered or composed?Decorator
ArchitecturalHow should the whole application be separated?MVC

A Business-Friendly Mental Model

Think of patterns as management roles inside software:

  • Factory is HR: it hires the right kind of worker.

  • Strategy is leadership choice: it decides which plan to use today.

  • Observer is company communication: it broadcasts important events.

  • Decorator is value-added packaging: it wraps the same product with extra features.

  • MVC is organizational structure: it separates data, decisions, and presentation.


Quick Comparison Table

PatternBest used whenMain strengthCommon mistake
FactoryYou build related objects repeatedlyCentralized creationTurning every constructor into a factory
StrategyYou need interchangeable algorithmsEasy behavior switchingHiding simple logic behind too many classes
ObserverMany listeners depend on one eventLoose couplingForgetting unsubscribe or notification order
DecoratorYou want layered featuresFlexible compositionConfusing it with Python @decorator syntax
MVCYou want clean app boundariesSeparation of concernsLetting controllers become god objects

Visual Learning Roadmap


Interactive Warm-Up

What this demonstrates

The Checkout class stays the same while the payment behavior changes. That is the heart of the Strategy Pattern.


Mini Quiz

  1. Which pattern is most useful when object creation logic is scattered across many files?

  2. Which pattern helps many services react to one business event?

  3. Which pattern helps you add features around an existing object without changing its core implementation?

Answer Check
  1. Factory

  2. Observer

  3. Decorator


Practice Prompt

Suppose you are building an e-commerce platform. Match the problem to the right pattern:

  • Product export can be CSV, Excel, or PDF.

  • Price rules change for retail, wholesale, and loyalty customers.

  • Order creation should trigger email, analytics, and inventory updates.

  • Premium support should wrap the same customer account object.

  • Dashboard pages should separate business logic from page rendering.

One Possible Mapping
  • Factory for exporters

  • Strategy for pricing rules

  • Observer for order events

  • Decorator for premium support features

  • MVC for dashboard structure


Interactive Code

Expected output
Create the right exporter for a report -> Factory
Switch pricing logic by customer type -> Strategy
Notify analytics and inventory after an order -> Observer
Wrap a service with logging and caching -> Decorator

Guided Practice

Which pattern fits best when one checkout event should trigger inventory updates, customer email, and analytics logging?

Factory Factory helps with object creation, not event fan-out.
Observer Observer is designed for one event source and many downstream reactions.
Decorator Decorator layers features around one object rather than notifying many listeners.
MVC MVC separates application responsibilities, but it is not the best answer for event broadcasting.

Exercises

  1. Write one scenario from your own domain and name the pattern that fits best.

  2. Refactor the starter function below so it returns the right pattern for each case.

Exercise hint

Look for the core design tension in each sentence: creation, interchangeable behavior, broadcasting events, layering features, or application structure.


What Comes Next

The next notebooks move from overview to application:

  • Factory: create the right object cleanly

  • Strategy: swap algorithms without rewriting the caller

  • Observer: notify interested systems when events happen

  • Decorator: stack features without inheritance chaos

  • MVC: organize complete applications clearly