Intro to Design Patterns
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 90 of 104.
Design patterns are proven, reusable solutions to common problems that arise in software design. They aren't code you copy directly - they're templates or blueprints that describe how to structure classes and objects to solve specific challenges elegantly.
The concept was popularized by the "Gang of Four" (GoF) in their 1994 book, which cataloged 23 fundamental patterns. These patterns are typically grouped into three categories:
| Category | Purpose | Examples |
|---|---|---|
| Creational | Object creation mechanisms | Singleton, Factory, Builder |
| Structural | Class and object composition | Adapter, Decorator, Composite |
| Behavioral | Object interaction and responsibility | Observer, Strategy, Command |
Why learn design patterns? They provide a shared vocabulary among developers - saying "use a Factory here" instantly communicates a complex idea. They also help you avoid reinventing solutions and make your code more flexible and maintainable.
In C++, design patterns leverage the OOP features you've already learned: inheritance, polymorphism, abstract classes, and templates. Over the next lessons, you'll implement several essential patterns and understand when each one is the right tool for the job.
Challenge
EasyLet's build a simple pattern classifier that demonstrates your understanding of the three design pattern categories. You'll create a system that takes a pattern name and identifies which category it belongs to—Creational, Structural, or Behavioral—along with a brief description of that category's purpose.
You'll organize your code across three files:
PatternCategory.h: Define an abstract base class calledPatternCategorythat represents a design pattern category. It should have:- A pure virtual method
getName()that returns the category name as a string - A pure virtual method
getPurpose()that returns a description of what patterns in this category do - A virtual destructor
Then create three derived classes that inherit from
PatternCategory:CreationalCategory— returns name"Creational"and purpose"Object creation mechanisms"StructuralCategory— returns name"Structural"and purpose"Class and object composition"BehavioralCategory— returns name"Behavioral"and purpose"Object interaction and responsibility"
- A pure virtual method
PatternClassifier.h: Create aPatternClassifierclass that can identify which category a given pattern belongs to.Your classifier should have a method
classifythat takes a pattern name (string) and returns a pointer to the appropriatePatternCategory. Use smart pointers (std::unique_ptr) for memory management.The classifier should recognize these patterns:
- Creational:
Singleton,Factory,Builder - Structural:
Adapter,Decorator,Composite - Behavioral:
Observer,Strategy,Command
If the pattern name isn't recognized, return
nullptr.- Creational:
main.cpp: Read a single input—the name of a design pattern.Create a
PatternClassifierand use it to classify the input pattern. If the pattern is recognized, print:[PatternName] is a [CategoryName] pattern Purpose: [CategoryPurpose]If the pattern isn't recognized, print:
Unknown pattern: [PatternName]
For example, with input Singleton:
Singleton is a Creational pattern
Purpose: Object creation mechanismsWith input Observer:
Observer is a Behavioral pattern
Purpose: Object interaction and responsibilityWith input Proxy:
Unknown pattern: ProxyThis challenge reinforces the three categories of design patterns while practicing inheritance, polymorphism, and smart pointers—all concepts you've already mastered. The multi-file structure mirrors how real projects organize related classes.
Cheat sheet
Design patterns are reusable solutions to common software design problems. They serve as templates for structuring classes and objects, not direct code to copy.
Design patterns are grouped into three main categories:
| Category | Purpose | Examples |
|---|---|---|
| Creational | Object creation mechanisms | Singleton, Factory, Builder |
| Structural | Class and object composition | Adapter, Decorator, Composite |
| Behavioral | Object interaction and responsibility | Observer, Strategy, Command |
Benefits of design patterns:
- Provide a shared vocabulary among developers
- Avoid reinventing solutions to common problems
- Make code more flexible and maintainable
In C++, design patterns leverage OOP features including inheritance, polymorphism, abstract classes, and templates.
Try it yourself
#include <iostream>
#include <string>
#include "PatternClassifier.h"
int main() {
// Read the pattern name
std::string patternName;
std::cin >> patternName;
// TODO: Create a PatternClassifier instance
// TODO: Use the classifier to classify the input pattern
// TODO: If the pattern is recognized, print:
// "[PatternName] is a [CategoryName] pattern"
// "Purpose: [CategoryPurpose]"
// TODO: If the pattern is not recognized (nullptr), print:
// "Unknown pattern: [PatternName]"
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy10STL Overview
STL Overview & PhilosophySTL ContainersIteratorsSTL AlgorithmsFunctors & Lambda ExpressionsRecap - Word Frequency13Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory & Abstract FactoryBuilder PatternObserver PatternStrategy Pattern2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container