Reputation: 169
I'm learning the factory method,when and why to use,but one thing that was a little bit ambiguous is that why are we using the static keyword for the factory method,can somebody clarify. as shown in the code below:
enum VehicleType {
VT_TwoWheeler, VT_ThreeWheeler, VT_FourWheeler
};
// Library classes
class Vehicle {
public:
virtual void printVehicle() = 0;
static Vehicle* Create(VehicleType 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(VehicleType 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;
}
PS: This code can be found on GeeksForGeeks.
Upvotes: 2
Views: 122
Reputation: 811
Static method is one method for the type of the class. That means you don't need a variable for the class Vehicle
if you call Create
method. You call this method like that: Vehicle::Create(YOU_TYPE)
and not like 'regular' method with a class variable. Also Vehicle
have a pure virtual method, that's why you can't have a variable of this class and there so the method is static.
Upvotes: 1