Factory Method Pattern

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


download file now

Unknown

About Unknown

Author Description here.. Nulla sagittis convallis. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.

Subscribe to this Blog via Email :