Factory Method Examples

See the factory method implemented in some examples.

In this lesson, we’ll look at some examples of a simple factory method. We’ll make an interface (abstract class in the case of C++) named Window, and we will have two classes: DefaultWindow and Fancywindow, which will implement the Window. For object creation, we will have getNewWindow() as a concrete creator. Let’s take a look at its code.

We’ll create a factory method with simple pointers in this example.

Press + to interact
#include <iostream>
// Product
class Window{
public:
virtual Window* clone() = 0;
virtual ~Window() {};
};
// Concrete Products
class DefaultWindow: public Window {
public:
DefaultWindow() {
std::cout << "DefaultWindow" << '\n';
}
private:
DefaultWindow* clone() {
std::cout << "DefaultWindow clone" << '\n';
return new DefaultWindow();
}
};
class FancyWindow: public Window {
public:
FancyWindow() {
std::cout << "FancyWindow" << '\n';
}
private:
FancyWindow* clone() {
std::cout << "FancyWindow clone" << '\n';
return new FancyWindow();
}
};
// Concrete Creator or Client
Window* getNewWindow(Window& oldWindow) {
return oldWindow.clone();
}
int main(){
DefaultWindow defaultWindow;
FancyWindow fancyWindow;
const Window* defaultWindow1 = getNewWindow(defaultWindow);
const Window* fancyWindow1 = getNewWindow(fancyWindow);
delete defaultWindow1;
delete fancyWindow1;
}

Note: We can’t create the Window class object because it’s an abstract class.

Code explanation

  • Lines 4–8: We created a Window abstract class with one pure virtual method clone() and one virtual destructor.

  • Lines 11–21: We created a DefaultWindow class that implements the Window. We created a constructor containing no parameters, which ...