What is a Factory Pattern?
Factory Pattern take cares of the creation of objects and hides the implementation from the client. Think of a real factory that make cars and there are different type of cars eg. sedans, hatch backs, and suvs.

When do You Use it?
You should use this pattern when you have a code that creates new object of different type but each object has the same method. The code below is a client method called Buy() that has a switch statement that determine which type of car object to instantiate to get the price.

The problem with this code is that the client method needs to change if there is a new car type object added, and all the objects has the same method called GetPrice().

public decimal Buy(string carType, int qty)
{
	decimal price = 0.0;

	switch (carType)
	{
		case "sedan" :
			Sedan sedan = new Sedan();
			price = sedan.GetPrice();
			break;
		case "hatch" : 
			Hatch hatch = new Hatch();
			price = hatch.GetPrice();
			break;
	}

	return price * qty;
}

To solve this problem I am going to move the code that create the different car object away from the client and put it into its own class and call it CarFactory. The purpose of this separation is to create a decouple structure,  so that the sole responsibility of the CarFactory is just for creating new car objects and the client code only concern is the total cost of the purchase. In the future if you decide to add more car objects you only need to update the CarFactory class.

ICar Interface
Create a interface that defines a method called GetPrice() which returns a decimal value.

public interface ICar 
{
	decimal GetPrice();
}

Car Class
Create a Sedan and Hatch class that implements the ICar interface.

public class Sedan : ICar
{
	public decimal GetPrice()
	{
		return 20000;
	}
}

public class Hatch : ICar
{
	public decimal GetPrice()
	{
		return 14000;
	}
}

CarFactory Class
Create a factory class with a static method called GetCar() which will receive a string of car type. In the method there will be switch to determine which car to create and return the interface portion of that car class.

public static class CarFactory 
{
	public static ICar GetCar(string carType)
	{
		ICar car;
		decimal price = 0.0;
		switch (carType)
		{
			case "sedan" :
				car = new Sedan();
				break;
			case "hatch" : 
				car = new Hatch();
				break;
		}
		return car;
	}
}

Client Method
Back to our client method Buy(), it uses the static method GetCar() to return a ICar and client can call the interface method GetPrice() to get the price of the car.

public decimal Buy(string carType, int qty)
{
	ICar car = CarFactory.GetCar(carType);
	return car.GetPrice() * qty;
}

Summary
The factory pattern is commonly used pattern for creating objects. The factory class does all the hard work of creating objects while the client only cares about the getting the price of the particular car.

Source Code:

 

Shares