Introduction
This post describes the simple implementation of Abstract Factory Pattern using C++.
Intent
- Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products".
Problem
We all know about PCI (Peripheral Component Interconnect) and USB ( Universal Serial Bus) communication protocol mechanisms for
data transfer. Using this as an example, I have created an abstract interface for both protocols and access their respective methods.
UML Diagram
Background
- Design Patterns using GOF
- C++ Programming
- Mentor - Mr.K.Babu Senior Software Engineer, Qmax Test Equipments Pvt. Ltd.
Code
#include <iostream>
using namespace std;
class HWProduct
{
public:
virtual void readData()=0;
virtual void writeData()=0;
};
class USBProduct:public HWProduct
{
public:
USBProduct() {}
void readData()
{
cout << "USB Read"<<endl;
}
void writeData()
{
cout << "USB
Write"<<endl;
}
};
class PCIProduct:public HWProduct
{
public:
PCIProduct() {}
void readData()
{
cout << "PCI Read"<<endl;
}
void writeData()
{
cout << "PCI
Write"<<endl;
}
};
class HardwareFactory
{
public:
virtual HWProduct* getProduct()=0;
};
class USBFactory:public HardwareFactory
{
public:
HWProduct* getProduct()
{
return new USBProduct();
}
~USBFactory(){}
};
class PCIFactory:public HardwareFactory
{
public:
HWProduct* getProduct()
{
return new PCIProduct();
}
~PCIFactory(){}
};
class Application
{
public:
Application(HardwareFactory* factory)
{
HWProduct* product = factory->getProduct();
product->readData();
product->writeData();
delete product;
delete factory;
}
};
HardwareFactory* getHWFActory(short int FactoryID)
{
if(FactoryID == 1)
return new USBFactory();
else
return new PCIFactory();
}
int main()
{
Application
application(getHWFActory(2));
return 0;
}