C++ Factory Pattern

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 Classclass Shape {public:virtual void Draw() = 0;// Static class to create objects// Change is required only in this function to create a new object typestatic 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 circleShape* obj1 = Shape::Create("circle");// Give me a squareShape* obj2 = Shape::Create("square");obj1->Draw();obj2->Draw();}


I am circleI am square

Abstract Factory – Sample Program

#include <iostream>#include <string>using namespace std;// Abstract base classclass Mobile {public:virtual string Camera() = 0;virtual string KeyBoard() = 0;void PrintSpecs() {cout << Camera() << endl;cout << KeyBoard() << endl;}};// Concrete classesclass LowEndMobile : public Mobile {public:string Camera() {return "2 MegaPixel";}string KeyBoard() {return "ITU-T";}};// Concrete classesclass HighEndMobile : public Mobile {public:string Camera() {return "5 MegaPixel";}string KeyBoard() {return "Qwerty";}};// Abstract Factory returning a mobileclass 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();}


2 MegaPixelITU-T5 MegaPixelQwerty