The other day while trawling the archive of the web comic
xkcd (My thanks go out to
singe for showing me the light. It is GOOD!) I happened upon the comic that is the inspiration for this post.
Now before I get started, I have to mention that a while ago I studied Design Patterns, but I brushed then off as silly nuisance. Back then they were nothing more that people writing about obvious facts that any/everyone knows and seemed more general knowledge. What I have recently noticed is that that is EXACTLY what they are.
Design patterns common problems with solutions that can be used over and over again to solve them.
Back to the subject at hand: The web comic expresses a man’s (who must be a geek) unbelief and fascination of how a woman has a factory for creating more of herself. For those that have not noticed, this is along the lines of the
Factory Method Pattern, and that it the subject of this post.
Factory Method Pattern
The factory method pattern allows classes to defer instantiation to their subclass.
In the basic form, the factory method pattern involves a creator and a product. The product is an abstract representation of a group of products while the creator is the base class of a possible creator hierarchy. A user asks the creator for an instance of a product and the creator will return it as a product. Rather confused? Not to worry? Remember, we are talking about the factory method pattern. What do factories do? They create stuff? Some pretty black pictures may help.
As we can see from the above the Creator creates instances of Product. The user does not need to worry about how the concreteproduct is created or what type of product it is since the concretecreator will return the concreteproduct via its interface. The words polymorphasism spring to mind. The creator similarly reliese on the concretecreators to create the correct concreteproject. Each conctretecreator is responsible for its own conctreteproduct.
As I said at the beginning this is only the vanilla flavor of the factor method patter. Derivatives allow for the creator to return a default instance of the product and more excitingly for the creator to be told what type of product it should create.
As I typed that last sentence I could see a big switch statement appear in my mind.