Solution: Factory Method
Get a detailed explanation of the solutions to the factory methods exercises.
We'll cover the following...
Solution to the first problem
Here is the refactored code using std::shared_ptr
.
Press + to interact
#include <iostream>#include <memory>// Productclass Window{public:virtual std::shared_ptr<Window> clone() = 0;};// Concrete Productsclass 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 Clientauto 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 purevirtual
methodclone()
with astd::shared_ptr
return type. -
Lines 11–20: We created a
DefaultWindow
class derived from theWindow
parent class. We created a constructor with no parameters, ...