| Category | Patterns |
|---|---|
| Creational (object creation) | Singleton, Factory, Abstract Factory, Builder, Prototype |
| Structural (composition) | Adapter, Decorator, Facade, Proxy, Composite |
| Behavioural (communication) | Observer, Strategy, Command, Iterator, State |
class Database {
private:
Database() {} // no outside construction
public:
static Database& instance() {
static Database db; // created once, thread-safe (C++11)
return db;
}
Database(const Database&) = delete; // no copies
void operator=(const Database&) = delete;
};
Database &db = Database::instance();
class Shape { public: virtual void draw() = 0; virtual ~Shape() {} };
class Circle : public Shape { public: void draw() override { cout << "Circle\n"; } };
class Square : public Shape { public: void draw() override { cout << "Square\n"; } };
unique_ptr<Shape> createShape(const string &type) { // factory
if (type == "circle") return make_unique<Circle>();
return make_unique<Square>();
}
createShape("circle")->draw();
class Observer { public: virtual void update(const string &msg) = 0; };
class Channel {
vector<Observer*> subs;
public:
void subscribe(Observer *o) { subs.push_back(o); }
void publish(const string &msg) { for (auto *o : subs) o->update(msg); }
};