Factory Design Pattern


The factory design pattern is a type of creational pattern to create an object. In factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.


C++ Implementation

This example is a C++ implementation of the Shape example from tutorialpoints.

In this example, we are going to create a Shape interface and concrete classes implementing the Shape interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <string>
using namespace std;

class Shape {
public:
    virtual void draw() {}
};

class Rectangle : public Shape {
public:
    void draw() {
        cout << "Inside Rectangle draw() function." << endl;
    }
};

class Square : public Shape {
public:
    void draw() {
        cout << "Inside Square draw() function." << endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        cout << "Inside Circle draw() function." << endl;
    }
};

class ShapeFactory {
public:
    Shape* getShape(string shapeType) {
        if (shapeType == "Circle") {
            return new Circle();
        } else if (shapeType == "Rectangle") {
            return new Rectangle();
        } else if (shapeType == "Square") {
            return new Square();
        } else {
            return nullptr;
        }
    }
};

int main() {
    ShapeFactory* sf = new ShapeFactory();
    
    Shape* s1 = sf->getShape("Circle");
    s1->draw();

    Shape* s2 = sf->getShape("Rectangle");
    s2->draw();

    Shape* s3 = sf->getShape("Square");
    s3->draw();
}




Related Posts

Singleton Design Pattern

The singleton design pattern is a type of creational pattern...

Factory Design Pattern

The factory design pattern is a type of creational pattern...