Skip to main content

Factory Method


In this design pattern, a contract is defined for creating an object. All derieved classes who implements this policy(via virtual method or implementing an interface ) decide which object in a class heirarchy to instantiate.

class Creator
{
  virtual MyObject CreateObject();
}

Creator defines a contract that all its derieved classes expose a method "CreateObject" which should return an object which "IS" a MyObject.
class MyObject
{

}

class MyConcreteObject : MyObject
{

}

class MyOtherConcreteObject : MyObject
{

}

MyConcreteObject and MyOtherConcreObject are different flavour of MyObject.Each of the class share IS relationship with MyObject.
Let's implement few "Creators".
class MyConcereteObjectCreater : Creator
{
  virtual MyObject CreateObject()
  {
     return new MyConcreteObject();
  }
}


class MyOtherConcereteObjectCreater : Creator
{
  virtual MyObject CreateObject()
  {
    return new MyOtherConcreteObject();
  }
}
Now the module which requires different flavours of MyObject need not worry about the instantiation of MyObject. It delegates the responsibility to "Creator" classes and they decide which type of MyObject is created.
void SomeMethod(Creator bClass)
{
  MyObject myObject = bClass.CreateObject();
  // MyObject is specific to a particular Concrete Class
}

Advantages of Abstract Method:

  • Factory methods give a hook for providing an extended version of an object.
  • Connects parallel hierarchies (MyObject --> Creator)

Comments