1.简单工厂模式
场景描述:披萨店为例,沈阳的披萨店里面有蔬菜披萨和奶酪披萨两种口味的披萨,顾客需要下单(选自己喜欢口味的披萨),披萨需要准备材料、烘焙、切开、包装最后拿到披萨;
///披萨抽象类 public abstract class Pizza { public void Perpare() { Console.WriteLine("准备披萨..."); } public void bake() { Console.WriteLine("烘焙披萨..."); } public void cut() { Console.WriteLine("刀切披萨..."); } public void box() { Console.WriteLine("包装披萨..."); } } ///蔬菜披萨 public class VeggiePizza : Pizza { public VeggiePizza() { Console.WriteLine("VeggiePizza is Created"); } } //奶酪披萨 public class CheesePizza : Pizza { public CheesePizza() { Console.WriteLine("CheesePizza is Created"); } }
//披萨店 public class PizzaStore { SimplePizzaFactory factory; public PizzaStore(SimplePizzaFactory simpleFactory) { factory = simpleFactory; } public Pizza OrderPizza(string type) { Pizza pizza= factory.CreatePizza(type); pizza.Perpare();//准备材料 pizza.bake();//烘焙 pizza.cut();//切开 pizza.box();//包装 return pizza; } } ///“披萨工厂” public class SimplePizzaFactory { public Pizza CreatePizza(string pizzaType) { if (pizzaType == "Veggie") { return new VeggiePizza(); } else if (pizzaType == "Cheese") { return new CheesePizza(); } else { return null; } } }
2.工厂模式
场景变化:现在呢,由于市场比较火爆,打算在芝加哥和纽约开两家分店,由于地域性不同,人们的口味习惯也不同,如芝加哥的蔬菜披萨菜叶放的特别多,芝加哥的奶酪披萨奶酪放的特别多,纽约的蔬菜披萨不放蔬菜,纽约的奶酪披萨里面放些芥末等等吧
//芝加哥口味的奶酪披萨 class ChicagoCheesePizza:Pizza { public ChicagoCheesePizza() { Console.WriteLine("芝加哥口味的奶酪披萨被创建"); } } //芝加哥口味的蔬菜披萨 public class ChicagoVeggiePizza:Pizza { public ChicagoVeggiePizza() { Console.WriteLine("芝加哥风味的蔬菜披萨被创建"); } } //纽约口味的奶酪披萨 public class NYCheesePizza:Pizza { public NYCheesePizza() { Console.WriteLine("纽约风味的奶油披萨被创建"); } } //纽约口味的蔬菜披萨 public class NYVeggiePizza:Pizza { public NYVeggiePizza() { Console.WriteLine("纽约风味的蔬菜披萨被创建"); } }
分别建立纽约店与芝加哥店
//具有芝加哥口味的披萨店 public class ChicagoPizzaStore:PizzaStore { public override Pizza CreatePizza(string pizzaType) { if (pizzaType == "Veggie") { return new ChicagoVeggiePizza(); } else if (pizzaType == "Cheese") { return new ChicagoCheesePizza(); } else { return null; } } } //纽约口味的披萨店 public class NYPizzaStore : PizzaStore { public override Pizza CreatePizza(string pizzaType) { if (pizzaType == "Veggie") { return new NYVeggiePizza(); } else if (pizzaType == "Cheese") { return new NYCheesePizza(); } else { return null; } } }
测试一下:
class Program { static void Main(string[] args) { FactoryPartton.NewFolder1.PizzaStore store = new ChicagoPizzaStore(); store.OrderPizza("Cheese"); store.OrderPizza("Veggie"); store = new NYPizzaStore(); store.OrderPizza("Cheese"); store.OrderPizza("Veggie"); Console.ReadKey(); } }