Factory Design Pattern

The factory pattern is used when you want to separate the creation of objects from where they'll be used.

For example, say you have one object that must get a Triangle object and draw it on screen. It doesn't care about what the triangle's state is, just that it has a void Draw() method. Suppose further that you have many types of triangles, and they can all be 'drawn' onscreen. In order to separate the creation of triangle objects from the caller, we would use the Factory Design Pattern:

1.) Create an interface called ITriangle, with one method : void Draw()
2.) Have all types of Triangle implement ITriangle.
3.) Create an interface called ITriangleFactory with 1 method: ITriangle GetTriangle()
4.) Create a concrete 'factory' class for each type of Triangle, each of which implements ITriangleFactory, and returns a new instance of their respective triangle in their implementations of GetTriangle()...since each Triangle type implements ITriangle, each factory can return whatever type of triangle it wants.

Now you can easily add triangle types in the future and change the type that is drawn by the caller, without changing every line of code that references the triangle:

public void callerMethod(ITriangleFactory factory){
    ITriangle myNewTriangle = factory.GetTriangle();
    myNewTriangle.Draw();
}

In the above code, if you want to change the type of triangle drawn, simply change the type of factory passed into callerMethod(). The rest is already taken care of.

Cheers.

Comments

Popular Posts