CSC/ECE 517 Fall 2012/ch2b 2w36 av

From Expertiza_Wiki
Revision as of 22:25, 16 November 2012 by Vcorrei (talk | contribs)
Jump to navigation Jump to search

Factory Method pattern and the related patterns (Template, Prototype)

Factory Method

Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.[1]Factory method is thus a type of creational pattern. An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client. [7]

The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.[4]

Use of factory method pattern makes the code more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create[7]


UML Diagram

UML Diagram for factory method pattern

In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.