In my opinion, This is the most simplist design pattern of all and the most widely and incorrectly used pattern in both .NET and J2EE World.
Factory and Abstract Factory are two different patterns, .For Example, Abstract factories can be used to instantiate a Concrete Factory.
What qualifies a Factory:
- Co-ordinated Instantiation.
- Stateless
- Configurable
- Can be Secured
- Loosely coupled.
- Does not Act as Container / not Initiate Transaction. (some of you may disagree with me on this)
In .NET System.Activator & System.Runtime.Remoting.ObjectHandle classes is the right way to implement Factory (or Abstract Factory) pattern. Frameworks such as Spring, Castle etc., provide these implementation declaratively with Aspects.
For instance in Spring.net,
<object name="DomainObjectImplementationClass"
singleton="false"
type="ImplementationClass1, SpringDIExample" />
You may delaratively specify the factory requirement. When you don't make your factory / abstract factory implementation configurable, chances are you may end up with boilerplate factory creation code over and over again. Spring.NET, Castle etc., is an example of a framework that provides this support via Dependeny Injection thur a container.
What about Containers?
Simply put, Containers provide ability to wrap objects with other statefull services. You may even assume a container as a Controller/Facade layer. This provides loose coupling for the contained objects from becoming “aware of“ details such as Transactionality , security etc.,
Those Services contained / Managed by the Containers can be instantiated using a Factory. Such containers & Services are not only well defined and truely encapuslated , they are also avoild the application or service specific code from getting scattered all over the application.
Factories , DIs are great concepts to explore, DI's and Factories enables you to develop a product with high cohesion and loose coupling, which essentially translates to maintanibility and scalability.