Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Simple Implementation of Abstract Factory Pattern using C++

3.00/5 (2 votes)
5 Mar 2013CPOL 16.4K  
It describes Abstract Factory Pattern which picks up the common hardware interface for different communication protocol.

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

Image 1

Background

  1. Design Patterns using GOF
  2. C++ Programming
  3. Mentor - Mr.K.Babu Senior Software Engineer, Qmax Test Equipments Pvt. Ltd.

Code

C++
#include <iostream> 
using namespace std; 
// Abstract product 
class HWProduct
{
public:
    virtual void readData()=0;
    virtual void writeData()=0;
};
//Concrete USB Product
class USBProduct:public HWProduct
{
public:
    USBProduct() {}
    void readData()
    {
        cout << "USB Read"<<endl;
    }
    void writeData()
    {
        cout << "USB
        Write"<<endl;
    }
};

//Concrete PCI Product
class PCIProduct:public HWProduct
{
public:
    PCIProduct() {}
    void readData()
    {
        cout << "PCI Read"<<endl;
    }
    void writeData()
    {
        cout << "PCI
        Write"<<endl;
    }
};

// Abstract Factory
class HardwareFactory
{
public:
    virtual HWProduct* getProduct()=0;
};
// Concrete USB Factory
class USBFactory:public HardwareFactory
{
public:
    HWProduct* getProduct()
    {
        return new USBProduct();
    }
    ~USBFactory(){}
};
// Concrete PCI Factory
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)