×

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 enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.