🧩 C++ programming tutorial for beginners · Class 11 · Lesson 16 of 18 · Free
Design Patterns Basics in C++ – Singleton, Factory, Observer and Strategy
⏱ About 40 minutes · ▶ run real C++ here — nothing to install · no sign-in
In this lesson you will
- Explain what a design pattern is and when one is worth using
- Write a singleton, a factory, an observer and a strategy in C++
- Swap behaviour at run time with interfaces or lambdas
Every school has solved the same problems again and again: one timetable for everyone, a form that decides which ID card to print, a notice board that tells all classes at once. Programmers also meet the same problems again and again. Design patterns are named, tried-and-tested shapes of code for them.
What is the singleton pattern in C++?
A design pattern is not a library you download. It is a well-known way to arrange classes to solve a common problem. Knowing the names helps teams talk: "use a factory here".
A singleton makes sure a class has exactly ONE object, and gives one place to get it. Example: the school's settings, which every part of the program must share.
The constructor is private, so nobody else can create one. get() makes a static local object the first time it is called (C++ guarantees this happens once) and returns a reference to it. Copying is deleted. Be careful: a singleton is a global variable in disguise, so use it rarely.
Settings loaded Green Valley School, pass mark 40 Same object? yes
What is the factory pattern in C++?
A factory is a function (or class) whose job is to create objects. The caller says WHAT it wants, often as text from the user, and the factory decides WHICH class to build.
It returns a smart pointer to the base class (Lesson 14), so the caller never names the child classes. To add a new ticket type, you change only the factory.
For an unknown request the factory returns nullptr, and the caller checks for it. Try it: add a "general" ticket that costs Rs 150.
sleeper: Rs 450 3ac: Rs 1200 first: no such ticket
What is the observer pattern in C++?
In the observer pattern, one object (the subject) keeps a list of other objects (observers). When something changes, it tells all of them.
Think of the school notice board: classes subscribe once, and every new notice reaches all of them. The board does not need to know what each class does with it.
Observers implement a small interface (Lesson 13). The subject stores pointers to them and calls update() on each. Try it: subscribe a third class and post another notice.
11-A got: Sports day on Saturday 11-B got: Sports day on Saturday
💡 The board stores plain pointers but does not own the classrooms, so they must live longer than the board.
What is the strategy pattern in C++?
The strategy pattern puts each way of doing a job in its own class, behind one interface. The main object holds one strategy and can switch it while the program runs.
Here the canteen bill does not know how discounts work. It just asks its discount object. On a festival day, you plug in a different strategy without touching Bill.
Compare this with a long if/else chain inside Bill: every new offer would mean editing Bill again. (struct is a class whose members are public by default, handy for tiny classes.)
Pay Rs 200 Pay Rs 180
Can you use lambdas instead of classes for patterns in C++?
Often, yes. When a strategy is just one function, a lambda in a std::function (header <functional>) is shorter than an interface plus a class.
std::function<double(double)> means "anything that takes a double and returns a double". You can store lambdas in it, change it later and keep them in a map by name.
Patterns are tools, not rules. Use one when it makes the code simpler to change. If a plain function or an if is clearer, use that.
festival: Rs 550 none: Rs 600 student: Rs 540
💡 A map keeps its keys sorted, so the offers print in alphabetical order.
🤔 Predict the output
Think like C++: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
#include <iostream>
using namespace std;
class Counter {
Counter() {}
public:
int visits = 0;
static Counter& get() {
static Counter c;
return c;
}
};
int main() {
Counter::get().visits++;
Counter::get().visits++;
Counter& a = Counter::get();
a.visits++;
cout << Counter::get().visits << "\n";
return 0;
}
Question 2. What does this print?
#include <iostream>
#include <memory>
#include <string>
using namespace std;
struct Card { virtual string kind() const = 0; virtual ~Card() = default; };
struct StudentCard : Card { string kind() const override { return "student"; } };
struct StaffCard : Card { string kind() const override { return "staff"; } };
unique_ptr<Card> makeCard(int role) {
if (role == 1) return make_unique<StudentCard>();
if (role == 2) return make_unique<StaffCard>();
return nullptr;
}
int main() {
for (int role = 1; role <= 3; role++) {
auto c = makeCard(role);
cout << (c ? c->kind() : "none") << " ";
}
cout << "\n";
return 0;
}
Question 3. Each lambda is an observer. They are called in the order they subscribed. What does this print?
vector<function<void()>> listeners;
int total = 0;
listeners.push_back([&total]() { total += 10; });
listeners.push_back([&total]() { total *= 2; });
for (auto& f : listeners) {
f();
}
cout << total << "\n";🧩 Your challenge
Finish a strategy-based canteen bill. Write a FestivalDiscount strategy that takes Rs 50 off bills above Rs 500 (otherwise no change), and a ComboDiscount that takes 15% off. Then make the Bill print three totals for an order of Rs 600 using NoDiscount, FestivalDiscount and ComboDiscount. Expected output: No discount: Rs 600 Festival: Rs 550 Combo: Rs 510
No discount: Rs 600 Festival: Rs 550 Combo: Rs 510
⚠️ Common mistakes (and how to fix them)
❌ Wrong
#include <iostream>
using namespace std;
class Settings {
Settings() {}
public:
int passMark = 35;
static Settings& get() { static Settings s; return s; }
Settings(const Settings&) = delete;
};
int main() {
Settings s = Settings::get();
s.passMark = 40;
cout << Settings::get().passMark << "\n";
return 0;
}
Line 13: error: call to deleted constructor of 'Settings'
✅ Right
#include <iostream>
using namespace std;
class Settings {
Settings() {}
public:
int passMark = 35;
static Settings& get() { static Settings s; return s; }
Settings(const Settings&) = delete;
};
int main() {
Settings& s = Settings::get();
s.passMark = 40;
cout << Settings::get().passMark << "\n";
return 0;
}
Without & you would make a copy, a second object, which breaks the singleton. Deleting the copy constructor turns this into a compile error. Use a reference: Settings& s.
❌ Wrong
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Listener {
public:
virtual void update(const string& n) const { cout << "(nobody listening) " << n << "\n"; }
virtual ~Listener() = default;
};
class Classroom : public Listener {
public:
void update(const string& n) const override { cout << "11-A got: " << n << "\n"; }
};
int main() {
Classroom a;
vector<Listener> list;
list.push_back(a);
for (const Listener& l : list) l.update("Exam on Monday");
return 0;
}
Compiles and runs, but prints: (nobody listening) Exam on Monday ⏎
✅ Right
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Listener {
public:
virtual void update(const string& n) const { cout << "(nobody listening) " << n << "\n"; }
virtual ~Listener() = default;
};
class Classroom : public Listener {
public:
void update(const string& n) const override { cout << "11-A got: " << n << "\n"; }
};
int main() {
Classroom a;
vector<Listener*> list;
list.push_back(&a);
for (const Listener* l : list) l->update("Exam on Monday");
return 0;
}
A vector<Listener> stores copies of only the base part (slicing), so the child's update() is lost. Store pointers (or smart pointers) to keep the real object.
❌ Wrong
#include <iostream>
using namespace std;
class Discount {
public:
double apply(double a) const { return a; }
};
class StudentDiscount : public Discount {
public:
double apply(double a) const { return a * 0.9; }
};
void pay(const Discount& d) { cout << "Pay Rs " << d.apply(200) << "\n"; }
int main() {
StudentDiscount s;
pay(s);
return 0;
}
Compiles and runs, but prints: Pay Rs 200 ⏎
✅ Right
#include <iostream>
using namespace std;
class Discount {
public:
virtual double apply(double a) const { return a; }
virtual ~Discount() = default;
};
class StudentDiscount : public Discount {
public:
double apply(double a) const override { return a * 0.9; }
};
void pay(const Discount& d) { cout << "Pay Rs " << d.apply(200) << "\n"; }
int main() {
StudentDiscount s;
pay(s);
return 0;
}
Strategies only work through virtual functions. Without virtual, a Discount& always calls the base version, so the student discount is ignored.
📌 Remember
- A design pattern is a named, proven shape of code for a common problem.
- Singleton: one object, private constructor, static get() returning a reference.
- Factory: one function decides which class to create and returns a base-class pointer.
- Observer: a subject keeps a list and notifies every observer of a change.
- Strategy: swap the way a job is done through an interface — or a std::function lambda.
- Use a pattern only when it makes code simpler to change.
Finished the quiz and the challenge?
Questions students ask
What are design patterns in programming?
They are reusable solutions to problems that come up again and again, such as creating the right object or telling many objects about a change. The famous "Gang of Four" book from 1994 gave 23 of them names.
Why is the singleton pattern sometimes called bad?
A singleton acts like a global variable. Any code can change it, which makes bugs harder to track and code harder to test. Use it only for things that truly must be one, like settings.
Do I need design patterns to write C++?
No. Small programs rarely need them. They help when programs grow and many people work on them, because the names describe a whole design in one word.
What is the difference between factory and strategy?
A factory is about CREATING the right object. A strategy is about CHOOSING how a job is done. They are often used together: a factory can create the right strategy.