Monday, September 24, 2007

* Patterns : Factory Method Creational Pattern

It provides an interface for creating an object but lets subclass decide which class to instantiates. So, it can also be called as virtual constructor.

Consider the following class diagram :

ShapeCreator class provides an factory method to create objects of BaseShape. Client always uses ShapeCreator and BaseShape type variables to work on instances of derives classes.

The client looks like following :

    public class Client
{
ShapeCreator createsShape;
public void Run()
{
BaseShape shape;
createsShape = new CircleCreator();
shape = createsShape.CreateShape();
shape.WhoAmI();
}
}

The code of CircleCreator looks like following :

    public class CircleCreator : ShapeCreator
{
public override BaseShape CreateShape()
{
return new CircleShape();
}
}

The CircleCreator decides which class to instantiate in response to CreateShape() method.


Download full source code from here : Factory Method Creational Pattern

No comments:

Post a Comment