
THE ABSTRACT FACTORY PATTERN
A factory in real life constructs tangible objects, such as Furniture. Similarly, a factory in object
oriented programming constructs objects. When you use factories in your program, portions of
code that want to create a particular object ask the factory for an instance of the object instead of
calling the object constructor themselves. Abstract Factory pattern lets a class defer instantiation to
subclasses.
If we want to create a Table, we can write code like this
Furniture *ft = new Table;
But if we are going to make it work across other platform, we should write something like this
Furniture *ft = FurnitureFactory->createTableorChair();
#include <iostream>
using namespace std;
class Furniture
{
public:
virtual void create() = 0;
};
class Table: public Furniture
{
public:
void create()
{
cout<<"Create Table"<<endl;
}
};
class Chair:public Furniture
{
public:
void create()
{
cout<<"Create Chair"<<endl;
}
};
class Furniturefactory
{
public:
virtual Furniture* createTableorChair()=0;
};
class Tablefactory:public Furniturefactory
{
public:
Furniture* createTableorChair()
{
return new Table();
}
};
class Chairfactory:public Furniturefactory
{
public:
Furniture* createTableorChair()
{
return new Chair();
}
};
int main()
{
Furniturefactory *furniturefactory;
Furniture *table;
furniturefactory = new Tablefactory();
table = furniturefactory->createTableorChair();
table->create();
Furniture *chair;
furniturefactory = new Chairfactory();
chair = furniturefactory->createTableorChair();
chair->create();
return 0;
}
Output:
Create Table
Create Chair
The Furniturefactory object abstracts the process of creating Table .Furniturefactory is not limited to producing Furniture user can add more class according to the need in software.