Home > Article > Backend Development > The application of singleton mode and factory mode in C++ function overloading and rewriting
Singleton mode: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.
The application of singleton mode and factory mode in function overloading and rewriting in C
Function overloading
The singleton mode can be implemented through function overloading. The overloaded function has a different parameter list and thus returns a different instance.
class Singleton { public: static Singleton* getInstance() { if (instance_ == nullptr) { instance_ = new Singleton(); } return instance_; } static Singleton* getInstance(int arg) { if (instance_ == nullptr) { instance_ = new Singleton(arg); } return instance_; } private: Singleton() = default; Singleton(int arg); static Singleton* instance_; };
Practical case
Create two singleton objects: one with parameters and one without parameters.
int main() { Singleton* instance1 = Singleton::getInstance(); Singleton* instance2 = Singleton::getInstance(10); // 检查两个实例是否相同 if (instance1 == instance2) { std::cout << "两个实例相同" << std::endl; } else { std::cout << "两个实例不相同" << std::endl; } }
Function rewriting
Factory mode can be implemented through function rewriting. The rewritten function has Different implementations create different objects.
class Product { public: virtual ~Product() {} }; class ConcreteProductA : public Product { // ... }; class ConcreteProductB : public Product { // ... }; class Factory { public: virtual ~Factory() {} 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(); } };
Practical case
Create two factory objects, each object creates a different product type.
int main() { Factory* factory1 = new ConcreteFactoryA(); Product* product1 = factory1->createProduct(); Factory* factory2 = new ConcreteFactoryB(); Product* product2 = factory2->createProduct(); // 检查两个产品类型是否不同 if (typeid(*product1) != typeid(*product2)) { std::cout << "两个产品类型不同" << std::endl; } else { std::cout << "两个产品类型相同" << std::endl; } }
The above is the detailed content of The application of singleton mode and factory mode in C++ function overloading and rewriting. For more information, please follow other related articles on the PHP Chinese website!