I am no wise sage, but I'll take a crack at it..
Originally posted by Lord British:
Is the abstract factory pattern suitable for factories that only create one product?
Per GoF's definition, Abstract Factory pattern is best used to provide an interface to create families of related or dependent products.
For example, if we have a VehicleFactory that only produces cars, do we need an AbstractVehicleFactory that returns a VehicleFactory that has a method createCar()?
If you have only one factory (~ VehicleFactory), no need of AbstractVehicleFactory. On the other hand, if you have factories in USA, Canada, India, Mexico producing different products/families of products,
you will have an AbstractVehicleFactory, which, based on runtime parameters (~ at which physical factory you are running the application which make use of the interface provided by AbstractVehicleFactory), will return an instance of one of these classes -
USAVehicleFactory, CanadaVehicleFactory, IndiaVehicleFactory, MexicoFactory.
I can see that the abstract factory pattern is usefull for factories that create different products such as a VehicleFactory class that creates cars and motorcylces.
Yes, indeed.
An example of an abstract factory that only has a single product is the javax.xml.parsers.SAXParserFactory class.
Not entirely true. Usually the default factory implementation is used, but, if you set the javax.xml.parsers.SAXParserFactory system property,
or, modify <JRE_Location>/lib/jaxp.properties, or .. see
here at Java API documentation for more info, you can change the SAXParserFactory implementation (~USAVehicleFactory or CanadaVehicleFactory) used to create the instances of SAXParsers (~Car).
SAXParserFactory.newInstance() returns a concrete SAXParserFactory instance.
Actually the currently configured factory.
SAXParserFactory has a non static method newSAXParser() that returns a SAXParser.
It ia analogous to your newVehicle()
In this case, the only product it can create is a parser - nothing else.
This is not a limitation of the pattern.
Why do we even need to have an abstract factory in this case?
Could we not do something like this?
SAXParser parser = SAXParser.createParser();
Intead of this:
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
What you have quoted here is a standard example of a pattern called "Factory method", which meets a requirement different from that of the AbstractFactory design pattern.
Again the question is:
Is the abstract factory pattern suitable for factories that only create one product?
Why not? This pattern is used to mainly switch between factories at runtime. The fact that the factory interface/implementation
creates, or allows the creation of only one product is a trivial detail, if not completely irrelevant.
Perhaps some wise sage could shed some light on this matter - thanks.
[ June 04, 2003: Message edited by: Lord British ]
-GB.