Friday, August 03, 2007

Pattern Series - Part II - Factory Pattern

Factory pattern



We will discuss about the Factory pattern in this article. It would give clear better idea if we start the article with a non-software example.



A non-software example that demonstrates this pattern would be a restaurant. Restaurants serve a variety of items which they list in the menu. The restaurant's waiter provides a menu to the customer and, based on the items available in the Menu, the customer selects the items and orders them. These selected items are prepared and served to the customer by the waiter.



Intent:

A factory pattern is one that returns an instance of one of several possible classes depending on the data provided to it. Usually all of the classes it returns should have a common base class and common methods, but implementations of the methods may be different.



Also Known As: Virtual Constructor



Motivation:

Frameworks use abstract classes to define and maintain relationships between objects. A framework is often responsible for creating these objects as well.



Applicability:


Use the Factory Method pattern when,


  • A class can't anticipate the class of objects it must create.

  • A class wants its subclasses to specify the objects it creates.

  • Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Participants

Product :Defines the interface of objects the factory method creates.

ConcreteProduct : Implements the Product interface.

Creator : Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
May call the factory method to create a Product object.

ConcreteCreator :Overrides the factory method to return an instance of a ConcreteProduct.

Collaborations

Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.

Sample Code:

using System;

class Factory

{
public Base GetObject(int type)

{
Base base1 = null;switch(type)

{
case 1:
base1 = new Derived1();
break;

case 2:
base1 = new Derived2();
break;
}

return base1;
}

}

interface Base

{
void DoIt();

}

class Derived1 : Base

{
public void DoIt()

{
Console.WriteLine("Derived 1 method");

}
}

class Derived2 : Base

{
public void DoIt()

{
Console.WriteLine("Derived 2 method");

}

}

class MyClient

{
public static void Main()

{
Factory factory = new Factory();//Decides which object must create.

Base obj = factory.GetObject(2);

obj.DoIt();

}

}

Hope, this could have given an idea about Adapter Pattern. Meet you soon some other pattern.

Happy coding....

:))

Cheers....

No comments:

Post a Comment