When to use Factory method pattern?
Please provide me some specific idea when to use it in project? and how it is a better way over new keyword?
I think its when you want your application to be loosely coupled and extensible in future without coding changes.
I have written a post on blog as to why i choose the factory pattern in my project and may be it can give you more insight. The example is in PHP but i think its applicable in general to all languages.
http://www.mixedwaves.com/2009/02/implementing-factory-design-pattern/
I am using Factory pattens when
When a class does not know which class of objects it must create.
A class specifies its sub-classes to specify which objects to create.
In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.
It's better to have a factory method pattern vs new keyword. The idea is to move complete instantiation of objects outside the business logic. This principle is the crux of dependency injection. And, the work of the factory method can be delegated to a Dependency Injection Framework like Spring.net or Castle Windsor at a later point.
I have two cases where I tend to use it:
Examples:
First case could be that you want to have a factory creating SqlCommand
objects, where you automatically attach a valid SqlConnection
before returning the command object.
Second case is if you have an interface defined and determine at execution time which exact implementation of the interface to use (for instance by specifying it in a configuration file).