Tuesday, May 20, 2008

Factory Pattern

  • Factory pattern is a creational design pattern.
  • Idea of the factory patterns is to localize the object creation code.
  • This prevents disturbing the entire system for a new type introduction.
  • Typically when a new type is introduced in the system, change is at one place only where the object is created to decide which constructor to use.
  • Simplest of the factory is introduction of a static method in the base class itself, which creates the required object based on the type.
  • Other variant is Abstract Factory.
  • Concrete classes are isolated.
  • Client need not event know which class is implementing its need.

Static factory - Sample Program

#include <iostream>
#include <string>

using namespace std;

// Abstract Base Class
class Shape {
    public:
       virtual void Draw() = 0;

       // Static class to create objects
       // Change is required only in this function to create a new object type
       static Shape* Create(string type);
};

class Circle : public Shape {
    public:
       void Draw() { cout << "I am circle" << endl; }
       friend class Shape;
};

class Square : public Shape {
    public:
       void Draw() { cout << "I am square" << endl; }
       friend class Shape;
};

Shape* Shape::Create(string type) {
    if ( type == "circle" ) return new Circle();
    if ( type == "square" ) return new Square();
    return NULL;
}

void main()
{
   // Give me a circle
   Shape* obj1 = Shape::Create("circle");

   // Give me a square
   Shape* obj2 = Shape::Create("square");

   obj1->Draw();
   obj2->Draw();
}

OUTPUT:
I am circle
I am square

Abstract Factory - Sample Program

#include <iostream>
#include <string>

using namespace std;

// Abstract base class
class Mobile {
    public:
       virtual string Camera() = 0;
       virtual string KeyBoard() = 0;

       void PrintSpecs() {
          cout << Camera() << endl;
          cout << KeyBoard() << endl;
       }
};

// Concrete classes
class LowEndMobile : public Mobile {
    public:
       string Camera() {
          return "2 MegaPixel";
       }

       string KeyBoard() {
          return "ITU-T";
       }
};

// Concrete classes
class HighEndMobile : public Mobile {
    public:
       string Camera() {
          return "5 MegaPixel";
       }

       string KeyBoard() {
          return "Qwerty";
       }
};


// Abstract Factory returning a mobile
class MobileFactory {
    public:
       Mobile* GetMobile(string type);
};

Mobile* MobileFactory::GetMobile(string type) {
    if ( type == "Low-End" ) return new LowEndMobile();
    if ( type == "High-End" ) return new HighEndMobile();
    return NULL;
}


void main()
{
   MobileFactory* myFactory = new MobileFactory();

   Mobile* myMobile1 = myFactory->GetMobile("Low-End");
   myMobile1->PrintSpecs();

   Mobile* myMobile2 = myFactory->GetMobile("High-End");
   myMobile2->PrintSpecs();
}

OUTPUT:
2 MegaPixel
ITU-T
5 MegaPixel
Qwerty

Trending

Back to Top