Showing posts with label factory design pattern. Show all posts
Showing posts with label factory design pattern. Show all posts

Saturday, May 12, 2012

Factory Pattern. When to use factory methods?


I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.
So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.
So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.
In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
public interface IThingFactory
{
    Thing GetThing(string theString);
}

public class ThingFactory : IThingFactory
{
    public Thing GetThing(string theString)
    {
        return new Thing(theString, firstDependency, secondDependency);
    }
}
So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.
http://stackoverflow.com/questions/69849/factory-pattern-when-to-use-factory-methods

Saturday, January 9, 2010

Factory Design Pattern

Idea is you extract the volatile core code and put it into external factory object. Instead of configuring factory at the time of construction (usual in Java), GoF factory design pattern says you should be able to create a general factory and then set the type of connection at the time of connection creation.