Reputation: 45
The example for abstract factory would be production of Japaneses cars, there are left door, right door and Hood etc.
Since I use C++ a lot, I always thought it in directly way. LeftDoor, RightDoor and Hood classes, and with Model1 left door, Model2 left door inherits LeftDoor class, and so does RightDoor and Hood. then if we want to create Honda, we just need to inherit, such as Honda -> Model1 Left door, Model2 right door, Model3 hood. then it is done.
So my question is can we do it like that? if we can, why we use abstract factory?
Upvotes: 1
Views: 751
Reputation: 26419
then if we want to create Honda, we just need to inherit, such as Honda -> Model1 Left door, Model2 right door, Model3 hood. then it is done.
There's a problem with your logic. Car is not a door. Inheritance means "IS" relationship. If "A" inherits "B", then "A" is type of "B". Another problem is that door and hood are optional components. If you rip off a door, car is still car, plus you can replace doors with different components. You need to change the way of thinking. In this scenario car HAS a door, but it is not a door.
A more appropriate usage of multiple inheritance would be situation when you have class for "Amphibious vehicle" and it inherits "LandVehicle" and "Boat".
As for your "car model" situation, you need a car class that contains list of components. Then you need to create different sets of components for different car model. Those sets can be fed to a "builder" (see "Builder" pattern) as an argument in order to make car you want.
Upvotes: 0
Reputation: 258618
You should go with composition over inheritance here.
class Component;
class Door : public Component;
class LeftDoor : public Door;
class RightDoor : public Door;
class Car
{
vector<ComponentPtr> components;
}
class Honda : public Car
{
}
class CarFactory
{
CarPtr createCar(std::string make);
}
This is because Honda
is a Car
, and each Car
has a LeftDoor
and RightDoor
.
The factory merely creates Car
instances. So if you called CarFactor::createCar("Honda");
it would return an instance of Honda
.
Upvotes: 3
Reputation: 10789
For the example you have given I would implement Composition over Inheritance since a Honda car does not have a is-a relationship to a door. But rather than has-a relationship.
Upvotes: 2