Saturday, 9 June 2018

Factroy Creation DP

// A design without factory pattern/ A design without factory pattern
#include
#include
using namespace std;


enum vehicle_type {
    VT_TwoWheeler,
    VT_ThreeWheeler,
    VT_FourWheeler
};

// Library classes
class Vehicle {
public:
    virtual void printVehicle() = 0;
    static Vehicle* create(vehicle_type type);
};
class TwoWheeler : public Vehicle {
public:
    void printVehicle()  {
        cout << "I am two wheeler" << endl;
    }
};
class ThreeWheeler : public Vehicle {
public:
    void printVehicle()  {
        cout << "I am three wheeler" << endl;
    }
};
class FourWheeler : public Vehicle {
    public:
    void printVehicle()  {
        cout << "I am four wheeler" << endl;
    }
};


// Factory method to create objects of different types.
// Change is required only in this function to create a new object type
Vehicle* Vehicle::create(vehicle_type type) {
    if (type == VT_TwoWheeler)
        return new TwoWheeler();
    else if (type == VT_ThreeWheeler)
        return new ThreeWheeler();
    else if (type == VT_FourWheeler)
        return new FourWheeler();
    else
            return NULL;
}
// Driver program
int main() {
    Vehicle *pVehicle = Vehicle::create(VT_ThreeWheeler);
        pVehicle->printVehicle();
}
                                                                                                                                                                                    60,1          Bot


                                                                                                                           7,0-1          5%

No comments:

Post a Comment