7/24/2011

Design Pattern - Factory Method

Definition
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

UML Class Diagram



Factory Method: when and where use it  
- Class constructors exist so that clients can create an instance of a class. There are situations however, where the client does not, or should not, know which one of several candidate classes to instantiate.  The Factory Method allows the client to use an interface for creating an object while still retaining control over which class to instantiate. 

- The key objective of the Factory Method is extensibility. Factory Methods are frequently used in applications that manage, maintain, or manipulate collections of objects that are different but at the same time have many characteristics in common.  A document management system, for example, is more extensible if you reference your documents as a collection of IDocuments. These documents may be Text files, Word documents, Visio diagrams, or legal papers. But they have in command that they have an author, a title, a type, a size, a location, a page count, etc. When a new document type is introduced it simply implements the IDocument interface and it will fit in with the rest of the documents.  To support this new document type the Factory Method may or may not have to be adjusted (depending on how it was implemented, that is, with or without parameters).  The example below will need adjustment.


- Factory Methods are frequently used in „manager‟ type components, such as, document managers, account managers, permission managers, custom control managers, etc.

- In your own programs you most likely have created methods that return new objects. However, not all methods that return a new object are Factory methods. So, when do you know the Factory Method is at work? The rules are:  

   + the method creates a new object
   + the method returns an abstract class or interface
   + the abstract class or interface is implemented by several classes  

Sample
- Employee

- Employee Subclass

- Company

- Company Subclass

- Main class



Ref: Gang of Four tutorial

No comments:

Post a Comment