139
CategoryPatterns
Creational (object creation)Singleton, Factory, Abstract Factory, Builder, Prototype
Structural (composition)Adapter, Decorator, Facade, Proxy, Composite
Behavioural (communication)Observer, Strategy, Command, Iterator, State
Singleton: exactly one object C++ 13 lines
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();
Factory: hide which class is created C++ 9 lines
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();
Observer: notify all subscribers C++ 8 lines
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); }
};