Solution: Factory Method

Get a detailed explanation of the solutions to the factory methods exercises.

Solution to the first problem

Here is the refactored code using std::shared_ptr.

Press + to interact
#include <iostream>
#include <memory>
// Product
class Window{
public:
virtual std::shared_ptr<Window> clone() = 0;
};
// Concrete Products
class DefaultWindow: public Window {
public:
DefaultWindow() {
std::cout << "DefaultWindow" << '\n';
}
private:
std::shared_ptr<Window> clone() override {
return std::make_shared<DefaultWindow>();
}
};
class FancyWindow: public Window {
public:
FancyWindow() {
std::cout << "FancyWindow" << '\n';
}
private:
std::shared_ptr<Window> clone() override {
return std::make_shared<FancyWindow>();
}
};
// Concrete Creator or Client
auto getNewWindow(std::shared_ptr<Window> oldWindow) {
return oldWindow->clone();
}
int main() {
std::shared_ptr<Window> defaultWindow = std::make_shared<DefaultWindow>();
std::shared_ptr<Window> fancyWindow = std::make_shared<FancyWindow>();
auto defaultWindow1 = getNewWindow(defaultWindow);
auto fancyWindow1 = getNewWindow(fancyWindow);
}

Code explanation

  • Lines 4–8: We created a Window base class with one pure virtual method clone() with a std::shared_ptr return type.

  • Lines 11–20: We created a DefaultWindow class derived from the Window parent class. We created a constructor with no parameters, ...