一、定義
簡單工廠其實不是一個設計模式,反而比較像是一種編程習慣。
二、類圖
三、示例
/// <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
如若轉載,請保留原文地址。謝謝合作。