Factory Method Pattern

Factory Method pattern comes under creational pattern.

According to Gang Of Four intent of Factory Method pattern is to Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

SAMPLE CODE:

#include <iostream>

using namespace std;

enum LaptopType { APPLE, DELL, HP };

class Laptop {
public:
    virtual void info() = 0;
};

class Apple : public Laptop {
    void info() {
        cout << "Apple Laptop Approved" << endl;
    }
};

class Dell : public Laptop {
    void info() {
        cout << "Dell Laptop Approved" << endl;
    }
};

class Hp : public Laptop {
    void info() {
        cout << "HP Laptop Approved" << endl;
    }
};

Laptop * getLaptopFactory(LaptopType choice)
{
    Laptop * laptopObj;
    if (choice == APPLE) {
        laptopObj = new Apple();
    }
    else if (choice == DELL) {
        laptopObj = new Dell();
    }
    else if (choice == HP) {
        laptopObj = new Hp();
    }
    else {
        laptopObj = NULL;
    }
    return laptopObj;
}

int main()
{
    Laptop * emp1Laptop;
    emp1Laptop = getLaptopFactory(DELL);
    emp1Laptop->info();

    Laptop * emp2Laptop;
    emp2Laptop =  getLaptopFactory(APPLE);
    emp2Laptop->info();
}

OUTPUT:

Dell Laptop Approved
Apple Laptop Approved

No comments:

Post a Comment