'Factory method in C++: why additional Creator interface and does factory method need a class?
I am currently unclear what constitutes the Factory Pattern in C++ given many implementations and examples in the wild.
https://refactoring.guru/design-patterns/factory-method/cpp/example gives an example which is one step more complex (as it implements abstract class Creator and then for each of the two product types a separate inherited creator classes) than many other I have seen e.g.: here: https://sourcemaking.com/design_patterns/factory_method/cpp/1
I have adapted the code from https://refactoring.guru/design-patterns/factory-method/cpp/example by keeping just one Creator class and using the switch statement to decide which class to return.
- Does the below still implement the Factory Design Pattern?
- Do I even need
Creatorclass in my implementation - theFactoryMethod()could be just a function. - What is the true purpose of the abstract
Creatorclass in https://refactoring.guru/design-patterns/factory-method/cpp/example and does using it actually make the pattern into Abstract Factory?
#include <iostream>
class Product {
public:
virtual ~Product() {}
virtual std::string Operation() const = 0;
};
class ConcreteProduct1 : public Product {
public:
std::string Operation() const override {
return "ConcreteProduct1 is in operation.\n";
}
};
class ConcreteProduct2 : public Product {
public:
std::string Operation() const override {
return "ConcreteProduct2 is in operation.\n";
}
};
class Creator {
public:
virtual ~Creator() {};
public:
Product* FactoryMethod(int id) const {
switch (id){
case 1:
return new ConcreteProduct1();
case 2:
return new ConcreteProduct2();
default:
break;
}
}
};
int main() {
std::cout << "Launched with Creator - generating Product 1.\n";
Creator creator;
Product* prod1 = creator.FactoryMethod(1);
std::cout << prod1->Operation();
std::cout << "Launched with Creator - generating Product 2.\n";
std::cout << "(Using the same instance of Creator)\n";
Product* prod2 = creator.FactoryMethod(2);
std::cout << prod2->Operation();
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
