Abstract Factory is an extension to Factory Design Pattern discussed earlier. In fact the last method discussed in that post is nothing but an example of Abstract Factory design.
If the product being produced in the factory requires to set up a separate factory (for a particular product) itself, then the case is fit for Abstract Factory.
Main difference between factory and Abstract Factory is that:
The UML diagram of Factory pattern is
The UML diagram of Abstract factory is (taking example from Automobile industry)
(We are assuming that Bajaj produces car also).
Since both Bajaj & Mahindra factories are Automobile factories, they will be having the same interface and some common implementation.
Hence the interface of factories is defined in the Abstract Factory (IAutomobileManufacturer) and the concrete factories (BajajMotors, MahindraMotors) produces concrete products.
In Bikes category, Mahindra Factory produces MahindraScooty and Bajaj factory produces Pulsar. The advantage of this design is that in most cases, user need not bother about which factory he is calling and which byke he is using.
A sample code can be
/** * Start a particular Bike by knowing just the factory. */ void startBike(IAbstractFactory fac) { IBike bk = fac.getBike(); bk.start(); }
Both the concrete classes of bikes will implement start function.
class IBike { public: virtual void start(); }; class Pulsar : public IBike { .. defining the start method }; class MahindraScooty : public IBike { .. defining the start method };
Hence user will be transparent from which Byke he is actually dealing with, the byke will still start.
Abstract Factory pattern allows you to create a groups of products without having to know the actual class of the product being produced.
The result is that you can have client code that does not need to be changed when the internal logic of the factories on which product to produce changed.
The fact that the factory returns an abstract pointer to the created object means that the client doesn’t have and does not need to have knowledge of the object’s type.
Mixing the patterns:
Ususlly only one instance of ConreteFactory (BajajMotors, MahindraMotors) is required, hence it is a good idea to make Concrete Factory class a Singleton.