Factory Design Pattern
Today I'm going to show you a very simple code segment to understand the one of the most used design pattern in the IT word. As I mention on the Title it's Factory pattern and the main intent of this pattern is to create objects without exposing to the client and also refers to newly created object through a common interface. in this article I'm not going to explain you the theoretical parts. so I'm going to show you sample code now. here I use the famous Pizza story to come up with a solution. and you can get more details about this pattern here.
1. Create a IFactory Interface
2. Create Domino's Class and Implement it using IFactory Interface
3. Create Pizza Hut Class and Implement it using IFactory Interface
4. Create Enum for the Product type and the Factory Class
5. Main Method
7. Final Output
That's all about Factory pattern. simple huh? okay now you can use this pattern. have a good day and see you guys soon.
1. Create a IFactory Interface
/// <summary>
/// IFactory Interface
/// </summary>
public interface IFactory
{
/// <summary>
/// Pizza Create Method
/// </summary>
/// <returns></returns>
string CreatePizza();
}
2. Create Domino's Class and Implement it using IFactory Interface
/// <summary>
/// Domino Class
/// </summary>
public class Domino : IFactory
{
/// <summary>
/// Pizza Create Method
/// </summary>
/// <returns>Domino's Pizza</returns>
public string CreatePizza()
{
return "Domino's Pizza";
}
}
3. Create Pizza Hut Class and Implement it using IFactory Interface
/// <summary>
/// Domino Class
/// </summary>
public class Domino : IFactory
{
/// <summary>
/// Pizza Create Method
/// </summary>
/// <returns>Domino's Pizza</returns>
public string CreatePizza()
{
return "Domino's Pizza";
}
}
4. Create Enum for the Product type and the Factory Class
/// <summary>
/// Pizza Factory Type
/// </summary>
public enum PizzaFactoryType
{
PizzaHut,
Dominio
}
/// <summary>
/// Factory Class
/// </summary>
public class Factory
{
/// <summary>
/// The factory instance
/// </summary>
private IFactory factory;
/// <summary>
/// Pizza create method
/// </summary>
/// <param name="type">Pizza Factory Type.</param>
/// <returns></returns>
public IFactory CreateFactory(PizzaFactoryType type)
{
switch (type)
{
case PizzaFactoryType.PizzaHut:
factory = new PizzaHut();
break;
case PizzaFactoryType.Dominio:
factory = new Domino();
break;
}
return factory;
}
}
5. Main Method
class Program
{
/// <summary>
/// Main Methods
/// </summary>
static void Main()
{
var factory = new Factory();
var pizzaFcatory1 = factory.CreateFactory(PizzaFactoryType.Dominio);
var pizzaFcatory2 = factory.CreateFactory(PizzaFactoryType.PizzaHut);
Console.WriteLine(pizzaFcatory1.CreatePizza());
Console.WriteLine(pizzaFcatory2.CreatePizza());
Console.ReadLine();
}
}
7. Final Output
That's all about Factory pattern. simple huh? okay now you can use this pattern. have a good day and see you guys soon.
Comments
Post a Comment