一、定义
简单工厂其实不是一个设计模式,反而比较像是一种编程习惯。
二、类图
三、示例
/// <summary>
/// 披萨商店
/// </summary>
public class PizzaStore
{
public PizzaStore()
{
}
public Pizza OrderPizza(string type)
{
Pizza pizza;
pizza = SimplePizzaFactory.CreatePizza(type);
pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();
return pizza;
}
}
/// <summary>
/// 披萨工厂
/// </summary>
public static class SimplePizzaFactory
{
public static Pizza CreatePizza(string type)
{
Pizza pizza = null;
if (type.Equals("cheese"))
{
pizza = new CheesePizza();
}
else if (type.Equals("pepperoni"))
{
pizza = new PepperoniPizza();
}
return pizza;
}
}
/// <summary>
/// 抽象披萨
/// </summary>
public abstract class Pizza
{
public abstract void Prepare();
public abstract void Bake();
public abstract void Cut();
public abstract void Box();
}
/// <summary>
/// 芝士披萨
/// </summary>
public class CheesePizza:Pizza
{
public override void Prepare()
{
Console.WriteLine("准备芝士披萨");
}
public override void Bake()
{
Console.WriteLine("烘培芝士披萨");
}
public override void Cut()
{
Console.WriteLine("切芝士披萨");
}
public override void Box()
{
Console.WriteLine("打包芝士披萨");
}
}
/// <summary>
/// 意大利香肠披萨
/// </summary>
public class PepperoniPizza:Pizza
{
public override void Prepare()
{
Console.WriteLine("准备意大利香肠披萨");
}
public override void Bake()
{
Console.WriteLine("烘培意大利香肠披萨");
}
public override void Cut()
{
Console.WriteLine("切意大利香肠披萨");
}
public override void Box()
{
Console.WriteLine("打包意大利香肠披萨");
}
}
static void Main(string[] args)
{
PizzaStore pizzaStore = new PizzaStore();
Pizza pizza = pizzaStore.OrderPizza("cheese");
Console.ReadLine();
}
原文:http://www.cnblogs.com/dongyang/p/4106774.html