Design patterns are tried-and-tested solutions to common software design problems. With the advent of modern C++ (C++11 and later), these patterns can be implemented more elegantly and efficiently, taking advantage of language features like lambda functions, smart pointers, and threading support. In this article, we'll explore three popular design patterns—Singleton, Observer, and Factory Pattern—and see how they can be applied using modern C++.
1. Singleton Pattern
Purpose
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.
Modern C++ Implementation
Using C++11's thread-safe static initialization, the Singleton pattern becomes simpler and safer to implement.

Results:

Key Points:
- The
staticlocal variable ensures thread-safe initialization. - Copy constructor and assignment operator are deleted to prevent multiple instances.
Advantages with Modern C++
- Simpler syntax compared to manual double-checked locking.
- Thread-safety is guaranteed out of the box.
2. Observer Pattern
Purpose
The Observer pattern allows an object (subject) to notify multiple dependent objects (observers) about changes in its state.
Modern C++ Implementation
Using std::function and std::vector makes it easier to manage observers and their callbacks.

Results:

Key Points:
std::functionallows for flexible observer callbacks.- Lambda expressions simplify observer registration.
Advantages with Modern C++
- Cleaner and more flexible observer management.
- Lambdas reduce boilerplate code.
3. Factory Pattern
Purpose
The Factory pattern provides an interface for creating objects without specifying their concrete classes.
Modern C++ Implementation
With smart pointers and std::unordered_map, factories in modern C++ can be made both safe and efficient.

Results:

Key Points:
std::make_uniqueensures memory safety and exception handling.std::unordered_mapand lambdas make product registration intuitive.
Advantages with Modern C++
- Memory management is simplified with smart pointers.
- Extending the factory is straightforward by adding new lambdas.
Conclusion
Modern C++ features such as smart pointers, lambda expressions, and thread-safe static initialization significantly enhance the implementation of traditional design patterns. They not only make the code more concise and readable but also reduce common pitfalls like memory leaks and thread-safety issues.
Exploring design patterns with modern C++ is an excellent way to understand the power of the language while adhering to best practices in software engineering. By combining these patterns with the features introduced in C++11 and beyond, developers can write more robust, efficient, and maintainable code.
References:
https://www.geeksforgeeks.org/singleton-pattern-c-design-patterns/
https://www.geeksforgeeks.org/factory-method-pattern-c-design-patterns/
https://www.geeksforgeeks.org/observer-pattern-c-design-patterns/