Factory design pattern in C++ is a creational design pattern which deals with creating objects without showing the exact class of object that is being created. This design pattern basically allows a class to defers the instantiation to sub-classes. For Design patterns basic explanation see (Design Patterns Simplified Version)
Generic model class diagram for Factory method design pattern can be explained as shown in image.
Factory method of design pattern is mainly useful in those scenarios where inheritance is involved.
These methods are also called as Template methods.
Factory Design Pattern Code Example:
Here we are explaining this design pattern with very basic example.
Let’s consider the problem statement where for creating an object for each type of animal.
Class diagram which solves this problem is as shown in image.
Let’s have a look on below classes which will act as concrete builder classes for factory class.
/* Base Class */
class Animal
{
public:
virtual void getDetails() = 0;
};
/* Derived classes */
class Cat:public Animal
{
public:
void getDetails()
{
cout << "Animal Cat created" << endl;
}
};
class Dog:public Animal
{
public:
void getDetails()
{
cout << "Animal Dog created" << endl;
}
};
class Lion:public Animal
{
public:
void getDetails()
{
cout << "Animal Lion created" << endl;
}
};
Let’s have a look onto factory class which will use above shown concrete classes to finally build the required object.
/* Factory Class */
class AnimalFactory
{
public:
Animal* getAnimal(string animalName)
{
/* Animal creation based on input*/
if(animalName == "Cat")
return new Cat();
else if(animalName == "Dog")
return new Dog();
else if(animalName == "Lion")
return new Lion();
else
cout << "ERROR: Unknown animal type selected" << endl;
return NULL;
}
};
Let’s see now how to use above classes to build the final product. Below code is sample “main” function code.
int main()
{
AnimalFactory *factory = new AnimalFactory();
string choice;
Animal *animal;
while(1)
{
cout << "Type animal name: Dog, Cat, Lion, exit" << endl;
cin >> choice;
if(choice == "exit")
break;
else
{
animal = factory->;getAnimal(choice);
if(animal)
{
animal->getDetails();
delete animal;
}
}
}
delete factory;
}
Output of the above example program:
Type animal name: Dog, Cat, Lion, exit
Dog
Animal Dog created
Type animal name: Dog, Cat, Lion, exit
Cat
Animal Cat created
Type animal name: Dog, Cat, Lion, exit