object의 생성부분을 처리하는 class를 factory로 한다.
특정한 객체를 만들어서 넘겨줄때, 또는 객체를 생성하고, 준비하는 과정에 대한 기본적인 내용이 필요한 경우에 Factory를 만들어서 Factory에서 처리하도록 한다.
using System;
namespace FactoryPattern1
{
public interface IPizzaStore
{
Pizza OrderPizza(string pizzaName);
}
public interface IPizzaFactory
{
Pizza CreatePizza(string pizzaName);
}
public class MyHomePizzaFactory : IPizzaFactory
{
#region IPizzaFactory Members
public Pizza CreatePizza(string pizzaName)
{
return new Pizza() { Name = pizzaName + " Sweet MyHome" };
}
#endregion
}
public class MyHomePizzaStore : PizzaStore, IPizzaStore
{
IPizzaFactory pizzaFactory;
public MyHomePizzaStore(IPizzaFactory pizzaFactory)
{
this.pizzaFactory = pizzaFactory;
}
#region IPizzaStore Members
public Pizza OrderPizza(string pizzaName)
{
Pizza pizza = pizzaFactory.CreatePizza(pizzaName);
PreparePizza(pizza);
CutPizza(pizza);
//this method is changable : in my home, we eat pizza with no boxing.
return pizza;
}
#endregion
}
public class HostwayPizzaFactory : IPizzaFactory
{
#region IPizzaFactory Members
public Pizza CreatePizza(string pizzaName)
{
return new Pizza() { Name = pizzaName + " HostwayPizza" };
}
#endregion
}
public class HostwayPizzaStore : PizzaStore, IPizzaStore
{
IPizzaFactory pizzaFactory;
public HostwayPizzaStore(IPizzaFactory pizzaFactory)
{
this.pizzaFactory = pizzaFactory;
}
#region IPizzaStore Members
public Pizza OrderPizza(string pizzaName)
{
Pizza pizza = pizzaFactory.CreatePizza(pizzaName);
PreparePizza(pizza);
CutPizza(pizza);
BoxingPizza(pizza);
return pizza;
}
#endregion
}
public abstract class PizzaStore
{
public string CutPizza(Pizza pizza)
{
return "Cutting Pizza";
}
public string PreparePizza(Pizza pizza)
{
return "Prepare Pizza";
}
public string BoxingPizza(Pizza pizza)
{
return "Boxing pizza";
}
}
public class Pizza
{
public string Name { get; set; }
}
}