C++
Module 33: Design Patterns in C++Advanced50 min read

Essential Design Patterns in Modern C++ (Singleton, Factory, Strategy, Observer)

Implement thread-safe Meyers' Singleton, Factory Method, Builder, Strategy, and Observer patterns idiomatically in Modern C++.

Key Takeaways & Core Concepts
  • Meyers' Singleton: Function-local static instance (thread-safe since C++11).
  • Factory & Abstract Factory: Return std::unique_ptr<Base> to decouple creation.
  • Builder: Fluent method chaining for complex configs.
  • Adapter, Decorator, Facade: Clean structural composition.

Essential Design Patterns in Modern C++ (Singleton, Factory, Strategy, Observer)

### 1. Creational, Structural & Behavioral Patterns in Modern C++

  • Meyers' Singleton: Function-local static instance (thread-safe since C++11).
  • Factory & Abstract Factory: Return std::unique_ptr<Base> to decouple creation.
  • Builder: Fluent method chaining for complex configs.
  • Adapter, Decorator, Facade: Clean structural composition.
  • Observer, Strategy, Command, State: Behavioral decoupling via interfaces or std::function.
1. Factory Pattern Returning unique_ptr
1#include <iostream>
2#include <memory>
3#include <string>
4
5struct Transport { virtual void deliver() const = 0; virtual ~Transport() = default; };
6struct Truck : Transport { void deliver() const override { std::cout << "Deliver by Truck\n"; } };
7struct Ship : Transport { void deliver() const override { std::cout << "Deliver by Ship\n"; } };
8
9std::unique_ptr<Transport> createTransport(const std::string& type) {
10 if (type == "sea") return std::make_unique<Ship>();
11 return std::make_unique<Truck>();
12}
13
14int main() {
15 auto t = createTransport("sea");
16 t->deliver();
17 return 0;
18}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
18 lines
Note: Encapsulates polymorphic creation behind a smart-pointer factory function.
Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)