Home > Pattern notes > Factory Pattern

Factory Pattern


Factory Pattern:

This is a part of creational pattern as it abstracts the creation object from the client.Provides an interface to create object but gives the ability to subclass to decide
which object to instantiate.

 let me put all this in diagram 

 

<br>
Here the client delegates the creation of object to the factory.

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.

If you map this non-software example against the factory design pattern, we can say:

Items, as the subclasses, are served to the customer by a waiter and its preparation is hidden from the customer.

The waiter, as the Factory class, takes the customer’s order based on the items available in the menu and serves them.

The customer, as the Client code, orders the items and does not see how the items are prepared.

The following sample application depicts one of the ways to implement the Factory design pattern in C#.

Sample code:

abstract class item

{

abstract Item PrepareItem()

}

class Pizza:Item

{

 public overide Item PrepareItem()

{

  return new Pizza()

}

}

class Bread:Item

{

 public overide Item PrepareItem()

{

  return new Bread()

}

}

Define Factory class:
Class ItemFactory
{
  public Item GetItem(int ItemCode)
{
Item items;
   switch(ItemCode)
{
     Case 1:
       items = new Bread();
     Case 2:
       items = new Pizza();
}
return items;
}
}
In the above listing, the factory class has one method, GetItem, which accepts one parameter. Based on the parameter value, one of the three Item implementations will be returned.  The client class is responsible for choosing which Item it would like to use.
Advertisements
Categories: Pattern notes
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: