views:

186

answers:

2

Hello,

I am trying to understand the Abstract Factory design pattern. I am having a lot of trouble with it. I am trying to use the following example to develop a UML class diagram:

Car designers can design many different types of cars. Cars can have two doors, or they can have four doors. Cars can be four-wheel drive, or they can be two-wheel drive. Cars are made up of different parts: wheels, doors, engine, transmission, etc. Each part has a different operation: For example, transmission can have first_gear(), second_gear(), third_gear(), fourth_gear(), reverse(), neutral().

The car parts (listed above) are available in Families: Honda, Jeep, Ford, etc.

Using the Abstract Factory design method, I need to develop a software system so that the system can easily change cars from one family to another.

Here is what I have been thinking so far: Having one factory, and multiple abstract factories. So, the abstract factories create the model, whereas the factory creates the parts...

Can anyone help? Thanks..

+2  A: 

There is a perfect example in HF design patterns check it out on google books for free. They use a pizza shop instead of a car factory but same idea. Taught me the pattern perfectly.

Head First Design Patterns

Lumpy
+1. Exactly what I was thinking of.
Andrew Coleson
+5  A: 

The design pattern for abstract factory means that you have one abstract factory and many implementations of "factories" that derive from it.

In your case, you'd probably have an abstract factory called VehicleFactory which would in turn be derived by HondaFactory, JeepFactory, FordFactory. In your example, you'd probably also have a class of objects that can be created from an abstract factory. Ex: TwoDoorCar, FourDoorCar. These classes would also be abstract and have concrete implementations like Ford2Door, HondaFourDoor. The point of the abstract factory is to abstract away the construction of these concrete objects. The method:

FourDoorCar VehicleFactory::CreateFourDoorCar() = 0;

would have concrete implementations like:

FourDoorCar HondaFactory::CreateFourDoorCar() { return new HondaFourDoor(); }

This way, all your create methods will be decided based on one line of code:

VehicleFactory factory = new HondaFactory();

instead of every place you create new four door and 2 door cars. Hope that helps.

Jordan
This is a great explanation. I opened the question because I wasn't 100% sure myself and left enlightened. Thanks!
MBillock
Happy to help :)
Jordan