According to the book:
The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.
Say I have a Creator class:
class Product; //this is what the Factory Method should return
class Creator {
public:
Creator() //ctor
{ //... }
virtual Product make(//args)
{ //... }
}
Ok, that's my Creator class, but I don't understand
The Factory method lets a class defer instantiation to subclasses
What does it have to do with subclasses? And what am I supposed to use subclasses for?
Anyone can give me some example?
Your
Creator
class is the factory. Let's call itProductFactory
, in order to make the example more explicit.(i am assuming you are using C++)
Call it like this:
So, to answer your question:
What the definition for factory pattern is saying is that the factory defines a common API for creating instances of a certain type (normally an interface or abstract class), but the real type of the implementations returned (thus the subclass reference) is the responsibility of the factory. In the example, the factory returns
Product
instances, for whichBook
andComputer
are valid subclasses.There are other idioms for factory, like having an API for the factory and the concrete implementations of the factory do not accept a
type
like in my example, but they are coupled with the type of instances returned, like this:In this class
BookProductFactory
always returnsBook
instances.To make it clear, since there seems to be a bit of confusion between
Abstract Factory
andFactory method
design patterns, let's see a concrete example:Using Abstract Factory
That is used like this:
Using Factory method
That is used like this:
When you use a
type
discriminator like I did in the original example, we are usingparametized factory methods
- a method that knows how to create different kind of objects. But that can appear in either anAbstract Factory
orFactory Method
pattern. A brief trick: if you are extending the factory class you are using Abstract Factory. If you extending the class with the creation methods, then you are using Factory Methods.