Advanced12 min readLesson 46 of 50
What are Design Patterns?
Design patterns are proven, reusable solutions to common software design problems. We cover three key patterns: Singleton, Factory, and Observer.
Singleton Pattern
Ensures only one instance of a class exists. Thread-safe using C++11 static initialization:
#include <iostream>
using namespace std;
class Logger {
private:
Logger() { cout << "Logger created\n"; }
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
public:
static Logger& getInstance() {
static Logger instance; // created once, thread-safe in C++11
return instance;
}
void log(const string& msg) { cout << "[LOG] " << msg << endl; }
};
int main() {
Logger::getInstance().log("App started");
Logger::getInstance().log("Processing...");
return 0;
}
Factory Pattern
Creates objects without specifying the exact class — decouples creation from use:
class Button { public: virtual void render() = 0; virtual ~Button(){} };
class WinButton : public Button { public: void render() override { cout << "[Windows Button]" << endl; } };
class MacButton : public Button { public: void render() override { cout << "[Mac Button]" << endl; } };
class ButtonFactory {
public:
static unique_ptr<Button> create(const string& type) {
if (type == "windows") return make_unique<WinButton>();
if (type == "mac") return make_unique<MacButton>();
throw invalid_argument("Unknown button type");
}
};
auto btn = ButtonFactory::create("mac");
btn->render(); // [Mac Button]
Observer Pattern
Defines a one-to-many dependency — when one object changes, all dependents are notified:
class Observer { public: virtual void update(int value) = 0; };
class EventSource {
vector<Observer*> observers;
int value = 0;
public:
void subscribe(Observer* o) { observers.push_back(o); }
void setValue(int v) {
value = v;
for (auto o : observers) o->update(v);
}
};
class Display : public Observer {
string name;
public:
Display(string n) : name(n) {}
void update(int v) override {
cout << name << " received: " << v << endl;
}
};
Quiz
What does the Singleton pattern guarantee?
- A) Fast object creation
- B> Only one instance of the class exists
- C) Thread safety by default
- D> Multiple factory methods
Answer
B) Singleton ensures only one instance is ever created.
Summary
- Singleton — one shared instance, lazy initialization.
- Factory — decouple object creation from usage.
- Observer — event-driven notification to multiple subscribers.