Common design patterns in C++ class design include: Singleton pattern: Ensure that a class has only one instance. Factory Method Pattern: Creates objects without specifying a concrete class, allowing subclasses to change the instantiation process. Observer pattern: Define one-to-many dependencies between objects. When one object changes, other dependent objects will receive notifications and update.
Design patterns are universal solutions to common problems in software design. They provide a structured and reusable approach to building software, improving code maintainability, scalability, and flexibility.
In C++, some commonly used design patterns include:
Sample code:
class Singleton { private: static Singleton* instance; Singleton(); public: static Singleton* getInstance(); void doSomething(); }; Singleton* Singleton::instance = nullptr; Singleton* Singleton::getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; }
Sample code:
class Product { public: virtual void operation() = 0; }; class ConcreteProductA : public Product { public: void operation() override { // ... } }; class ConcreteProductB : public Product { public: void operation() override { // ... } }; class Factory { public: virtual Product* createProduct() = 0; }; class ConcreteFactoryA : public Factory { public: Product* createProduct() override { return new ConcreteProductA(); } }; class ConcreteFactoryB : public Factory { public: Product* createProduct() override { return new ConcreteProductB(); } };
Sample code:
class Observable { public: virtual void addObserver(Observer* observer) = 0; virtual void removeObserver(Observer* observer) = 0; virtual void notifyObservers() = 0; }; class Observer { public: virtual void update(Observable* observable) = 0; }; class ConcreteObservable : public Observable { private: std::vector<Observer*> observers; public: void addObserver(Observer* observer) override { observers.push_back(observer); } void removeObserver(Observer* observer) override { observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end()); } void notifyObservers() override { for (auto observer : observers) { observer->update(this); } } void doSomething() { // ... notifyObservers(); } }; class ConcreteObserverA : public Observer { public: void update(Observable* observable) override { // ... } }; class ConcreteObserverB : public Observer { public: void update(Observable* observable) override { // ... } };
The above is the detailed content of What are the commonly used design patterns in C++ class design?. For more information, please follow other related articles on the PHP Chinese website!