Thursday, April 15, 2010

Abstract class factory design

A software design pattern, the abstract factory pattern allows a way to encapsulate a group of single factories that have a common idea. In regular usage, the client software produces a concrete implementation of the abstract factory and then applies the generic interfaces to create the concrete objects that are part of the theme. The client doesn't know (or care) which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage.


A good example of this would be an abstract factory class DocumentCreator that leaves interfaces to create a number of products (e.g. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is gained from a simple abstract class like Letter or Resume of which the client is well aware. The client code would get an appropriate instantiation of the DocumentCreator and call its factory methods. Each of the resulting objects would be produced from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would need to know how to handle only the abstract Letter or Resume class, not the specific version that it got from the concrete factory.

In software development, a Factory is the location in the code at which objects are constructed. The aim in employing the pattern is to isolate the creation of objects from their usage. This allows for new gained types to be introduced with no alteration to the code that uses the base class.

Use of this pattern makes it possible to alternate concrete classes without changing the code that uses them, even at runtime. Even so, employment of this pattern, as with similar design patterns, may lead in unnecessary complexity and extra work in the initial writing of code. Used correctly the "extra work" pays off in the second instance of using the Factory.

No comments: