×

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory object, we can create a new object without affecting the creation logic of the client side. Here the Client uses the same technique for creating a new object every time. 

 Here in this factory method, there is a need for the use of a static member function. We use the static member function for the return and creation of the instances. Also, with the help of the factory method, the user can hide the class module's details.

Here we can say that the factory method is a type of core principle used to create a new object, and that object allows the Client to create the object in the library. These objects are created in such a way that they do not have tight coupling between them and maintain a hierarchy class in the library function.

What is the meaning of libraries and clients? 

Here, the term library means it provides a third party by which the user can fetch some APIs, and the Client can call those public APIs to complete their tasks. We can take the example of different types of views in the android operating system.

Example:

#include <iostream>
using namespace std;




class Vehicle {
public:
               virtual void printVehicle() = 0;
};
class TwoWheeler : public Vehicle {
public:
               void printVehicle()
               {
                               cout << "I am two wheeler Vehicle" << endl;
               }
};
class FourWheeler : public Vehicle {
public:
               void printVehicle()
               {
                               cout << "I am four wheeler Vehicle" << endl;
               }
};




class Client {
public:
               Client(int type)
               {


                               
                               if (type == 1)
                                               pVehicle = new TwoWheeler();
                               else if (type == 2)
                                               pVehicle = new FourWheeler();
                               else
                                               pVehicle = NULL;
               }


               ~Client()
               {
                               if (pVehicle) {
                                               delete pVehicle;
                                               pVehicle = NULL;
                               }
               }


               Vehicle* getVehicle() { return pVehicle; }


private:
               Vehicle* pVehicle;
};




int main()
{
               Client* pClient = new Client(1);
               Vehicle* pVehicle = pClient->getVehicle();
               pVehicle->printVehicle();
               return 0;
}

Output:

Factory Method for Designing Pattern

What are the problems with theabove design? 

As we have seen in the above example, the Client can create either four wheelers or a two-wheeler vehicle object. Here the library also introduces a new object name ThreeWheeler to support the three-wheeler vehicle. So the Client will go to end up with a new object if the condition ladder creates a new object for the three-wheeler vehicle. So these types of changes are made up on the library side. So the user needs to make the changes on the client side also. This is a very bad practice for the programmer.

How do we avoid the problem? 

There is a technique by which we can avoid that problem. The solution is we have to create a static method. Let's undethand this by the below example.

Example 2

#include <iostream>
using namespace std;


enum VehicleType {
               VT_TwoWheeler, VT_ThreeWheeler, VT_FourWheeler
};


// Library classes
class Vehicle {
public:
               virtual void printVehicle() = 0;
               static Vehicle* Create(VehicleType type);
               virtual ~Vehicle(){}
};
class TwoWheeler : public Vehicle {
public:
               void printVehicle() {
                               cout << "I am two wheeler Vehicle" << endl;
               }
};
class ThreeWheeler : public Vehicle {
public:
               void printVehicle() {
                               cout << "I am three wheeler Vehicle" << endl;
               }
};
class FourWheeler : public Vehicle {
               public:
               void printVehicle() {
                               cout << "I am four wheeler Vehicle" << endl;
               }
};




Vehicle* Vehicle::Create(VehicleType type) {
               if (type == VT_TwoWheeler)
                               return new TwoWheeler();
               else if (type == VT_ThreeWheeler)
                               return new ThreeWheeler();
               else if (type == VT_FourWheeler)
                               return new FourWheeler();
               else return NULL;
}




class Client {
public:


               
               Client()
               {
                               VehicleType type = VT_ThreeWheeler;
                               pVehicle = Vehicle::Create(type);
               }
               ~Client() {
                               if (pVehicle) {
                                               delete pVehicle;
                                               pVehicle = NULL;
                               }
               }
               Vehicle* getVehicle() {
                               return pVehicle;
               }


private:
               Vehicle *pVehicle;
};




int main() {
               Client *pClient = new Client();
               Vehicle * pVehicle = pClient->getVehicle();
               pVehicle->printVehicle();
               delete pClient;
               return 0;
}

Output:

Factory Method for Designing Pattern

In the above example, we have totally decoupled the selection of types for object creation from the Client. The library is now responsible for deciding which object type to create based on input. The Client just needs to make calls to the library's factory Create method and pass the type it wants without worrying about the actual implementation of the creation of objects.


Related Topics

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.