Skip to content

Design_patterns

Design patterns are proven solutions to common software design problems. This chapter covers creational patterns.

Ensure only one instance exists:

class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
};
// Thread-safe C++11
class ThreadSafeSingleton {
private:
static std::atomic<ThreadSafeSingleton*> instance;
ThreadSafeSingleton() {}
public:
static ThreadSafeSingleton* getInstance() {
ThreadSafeSingleton* tmp = instance.load();
if (!tmp) {
tmp = new ThreadSafeSingleton();
}
return tmp;
}
};

Define interface for creating objects:

class Product {
public:
virtual void use() = 0;
};
class ConcreteProductA : public Product {
public:
void use() override { std::cout << "Using Product A\n"; }
};
class ConcreteProductB : public Product {
public:
void use() override { std::cout << "Using Product B\n"; }
};
class Factory {
public:
enum ProductType { A, B };
static Product* create(ProductType type) {
switch (type) {
case A: return new ConcreteProductA();
case B: return new ConcreteProductB();
}
return nullptr;
}
};

Separate construction from representation:

class Pizza {
std::string dough;
std::string sauce;
std::string topping;
public:
void setDough(const std::string& d) { dough = d; }
void setSauce(const std::string& s) { sauce = s; }
void setTopping(const std::string& t) { topping = t; }
};
class PizzaBuilder {
protected:
Pizza* pizza;
public:
virtual ~PizzaBuilder() {}
Pizza* getPizza() { return pizza; }
void createNewPizza() { pizza = new Pizza(); }
virtual void buildDough() = 0;
virtual void buildSauce() = 0;
virtual void buildTopping() = 0;
};
  • Singleton: One instance globally
  • Factory Method: Create objects without specifying exact class
  • Builder: Construct complex objects step by step