Showing posts with label abstract. Show all posts
Showing posts with label abstract. Show all posts

@since Monday, September 19, 2011

Factory Pattern

@throws 0 exception(s)
Continuing my series on Design Patterns (builder, strategy), I'll focus on one of the most commonly used patterns in object oriented programming - the Factory Pattern. 
In fact, there are actually 3 different patterns named factory (in some form): Factory Class, Abstract Factory, and the Factory Method. Each pattern has a different intention or use case but all handle the same problem of creating object instances during application runtime. Factories usually hold some creation logic and don't have much purpose if the object created can be easily constructed outside the factory.

Factory Class
Used to create an instance that is difficult to construct in normal initialization. Such difficulties may involve wrapping our instance with cache or other AOP operations. Some frameworks, such as Spring Framework use BeanFactory to initiate Beans by integrating with Spring's application context and provide the framework features on newly created Beans. A simple use case may be as follows:
Usually, it's good practice to hide your class construction from being accessed through different flows. A better way is to replace new with a factory class.

Abstract Factory
Next level of hiding our class initialization after the Factory Class. Here we're creating a hierarchy of factories that construct a super object (interface). We select the specific Factory Class to invoke during application runtime.
Factory Method
We've manage to hide the construction of objects from our use case flows but still our factories use new to construct the object. It is perfectly OK to initialize some objects with their constructor. There are times, however, when this isn't the best practice. For example, the constructor is too complicated, or we want to create a default instance with a particular set of arguments. In Java's Locale, such behavior is perfectly described in the Locale.getDefault() method, which constructs an object after reading system properties, without the user interacting with the object's constructor.
To summarize, it's good practice to hide your object construction in order to enhance your application modulation. Factories are perfect for that purpose but don't over use them or you'll end up having an empty layer around a simple object construction. Factories can also help in your clients' use cases by providing them with helpful construction methods (such as Factory Method or methods of a Factory Class).

Comments / Suggestions are welcome.