I try to implement the Factory Method Pattern in C++ while keeping a good level of abstraction. In the sample provided in the link, all derived classes are in the same file, but this is usually not the case.
-
Without header files for derived classes: To keep implementation details, I didn't provide a header file for the derived class (declaration & definition in the source file), then I don't see how to implement the factory method because the derived classes are not visible and forward declaration is not possible.
-
With header files for derived classes: I can implement the factory method, but the implementation details of derived classes leak because the private members and methods have to be declared in the header.
Maybe using the PImpl idom can help to solve the problem in case 2) but I wonder if this is correct/reasonable approach. What is the usual/best way to implement this pattern in C++ ?
Here is my code:
//graphic-api.hpp
class GraphicApi {
public:
enum class Type {
//OPENGL,
//DIRECTX,
VULKAN
};
virtual void render() = 0;
virtual ~GraphicApi() {};
static std::unique_ptr<GraphicApi> make(const Window& window, Type type);
};
//graphic-api.cpp
//need to include headers for derived classes
std::unique_ptr<GraphicApi> GraphicApi::make(const Window& window, GraphicApi::Type type) {
switch (type) {
case GraphicApi::Type::VULKAN:
return std::make_unique<VulkanApi>(window);
default:
assert(0 && "Unsupported Graphic API");
}
return nullptr;
}
//vulkan-api.hpp
class VulkanApi : public GraphicApi {
public:
VulkanApi(const Window& window);
virtual void render() {};
private:
// lot of private members & methods related to Vulkan API (not nice to see here)
vk::UniqueInstance instance;
...
};
Aucun commentaire:
Enregistrer un commentaire