Recall that the Factory Pattern is used to create object without specifying the exact class of the object, thus decreasing the coupling between those two components. The Abstract Factory Pattern even decreases the amount of de-coupling by defining an interface which all factories must implement. Thus the caller of the abstract factory doesn't know anything about the implementation of factory and how objects are created. The caller just nows, calling a method on the factory will yield a certain object instance of interface X.
The XML Library example from Matt is actually a good example. The abstract factory is the entity creating the XML parser which creates a Document
object representing the actual document you parse. Actually, for you as a caller, it is most of the time completely irrelevant which Parser is used, as long as you get a Document
object out of it. Therefore you can simply use the abstract factory. Which creates you a valid parser (most of the times ;))
The Toolkit example (also mentioned by Matt) is a more school-book like example. Imagine you just want to populate a window on the user screen. As you want to do it in a platform independent way, you define an abstract class Window with which you can do certain operations. Then you create an object which creates these windows, let's say Win32WindowsFactory
. However, as your code shall be platform-independet, you define an interface WindowsFactory
which provides you a method createWindow()
. When the Win32WindowsFactory
is used, a Win32Window
is returned, when a LinuxGTKWindowsFactory
is used, a GTKWindow
is returned.