Saturday, June 26, 2010

Factory Method - Pattern


Factory pattern - Here comes the most commonly quoted pattern Factory method (next to Singleton Pattern). Factory method is frequntly used in lot of real time scenarios especially in the framework libraries. While developing a reusable library which contains core/base implementation, there are times where we need to work with or maintain the relationship between objects which will be created later during the implentation of those libraries. I've discussed one such case below under the Implementation in .Net.

Ultimate aim is to create a Product object and work on it which will be available some time later (as specified above). The name Factory resembles the real-world factory since it holds the responsibility of creating the objects (Products). Simply speaking the Client uses the Factory method to create a specific type of Product.


Creator is the one who provides the interface for creating an object by holding the Factory method with him.
Factory method in the Creator returns a specific type of object Product.
Creator delegates the responsibility of "which class to be instantiated" to its subclass ConcreteCreator.
ConcreteCreator overrides the Factory method and it is responsible for creating the ConcreteProduct that adheres to the Product type. 



IEnumerable interface in .Net exposes a Factory method GetEnumerator(). The collection classes in .Net implements this IEnumerable interface to incur enumerator for a collection. Since foreach statement evaluates the type that implements IEnumerable, most of the collection classes will make use of this IEnumerable. ArrayList, HashTable, List,Dictionary are some of the examples.

IEnumerable needs to work on object of type IEnumerator, for iterating over the collection. Object of type IEnumerator knows how to iterate over the collection object of type IEnumerable.

ArrayList implements the IEnumerable and overrides the GetEnumerator method to create the object of ArrayListEnumeratorSimple which implements the IEnumerator.

Participants mapping

Creator : IEnumerable
ConcreteCreator : ArrayList
ConcreteProduct : ArrayListEnumeratorSimple
Product : IEnumerator


I've just focussed on the case of delegating the responsibility of creating the instances to the subclass. There are also cases where the factory method in the ConcreteCreator defines the default instantiation and parameterized Factory methods used to identify and create specific ConcreteProduct.


For references and more info:
Design Patterns: Elements of Reusable Object-Oriented Software
Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.