Design Patterns - EduardoMSU/OOP-2143 GitHub Wiki
Design patterns are reusable solutions to common problems in software design. They provide best practices and templates for solving recurring challenges, enhancing code reusability, maintainability, and scalability.
Category | Purpose | Examples |
---|---|---|
Creational Patterns | Focus on object creation mechanisms to increase flexibility and reuse. | Singleton, Factory Method, Builder, Prototype |
Structural Patterns | Deal with the composition of classes and objects to form larger structures. | Adapter, Bridge, Composite, Decorator |
Behavioral Patterns | Concerned with communication and responsibilities between objects. | Observer, Strategy, Command, State, Iterator |
Ensures a class has only one instance and provides a global point of access to it.
Feature | Explanation |
---|---|
Purpose | Prevents multiple instances of a class. |
Use Cases | Logging, configuration management, database connections. |
#include <iostream>
class Singleton {
private:
static Singleton* instance; // Static instance pointer
Singleton() {} // Private constructor
public:
// Method to get the single instance
static Singleton* getInstance() {
if (!instance)
instance = new Singleton();
return instance;
}
void showMessage() const {
std::cout << "Singleton instance accessed!" << std::endl;
}
};
// Initialize static member
Singleton* Singleton::instance = nullptr;
int main() {
Singleton* singleton = Singleton::getInstance();
singleton->showMessage();
return 0;
}