Design Patterns in C++: Practical Examples and Problem-solving Strategies

Design patterns are proven solutions to common programming problems. In C++, they help improve code organization, reusability, and maintainability. This article explores practical examples of popular design patterns and how they can be applied to solve real-world problems.

Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. It is useful for managing shared resources such as configuration settings or logging systems.

Example implementation:

Code:

“`cpp class Logger { private: static Logger* instance; Logger() {} public: static Logger* getInstance() { if (!instance) { instance = new Logger(); } return instance; } void log(const std::string& message) { // Log message } }; Logger* Logger::instance = nullptr; “`

Factory Method Pattern

The Factory Method pattern defines an interface for creating objects but allows subclasses to alter the type of objects that will be created. It promotes loose coupling and scalability.

Example scenario: creating different types of documents.

Code:

“`cpp class Document { public: virtual void create() = 0; virtual ~Document() {} }; class PDFDocument : public Document { public: void create() override { // Create PDF document } }; class WordDocument : public Document { public: void create() override { // Create Word document } }; class DocumentFactory { public: virtual std::unique_ptr createDocument() = 0; virtual ~DocumentFactory() {} }; class PDFFactory : public DocumentFactory { public: std::unique_ptr createDocument() override { return std::make_unique(); } }; class WordFactory : public DocumentFactory { public: std::unique_ptr createDocument() override { return std::make_unique(); } }; “`

Observer Pattern

The Observer pattern establishes a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically. It is useful for implementing event handling systems.

Example: a simple event system where multiple observers respond to a change.

Code:

“`cpp #include #include class Observer { public: virtual void update() = 0; virtual ~Observer() {} }; class Subject { private: std::vector observers; public: void attach(Observer* observer) { observers.push_back(observer); } void notify() { for (auto* observer : observers) { observer->update(); } } }; “`