简单工厂
用C#/.net core实现简单工厂
- Pizza的父类 ``` using System; using System.Collections.Generic;
namespace SimpleFactory.Pizzas {
public abstract class Pizza { public string Name { get; protected set; } public string Dough { get; protected set; } public string Sauce { get; protected set; } protected List<string> Toppings = new List<string>(); public void Prepare() { Console.WriteLine($"Preparing: {Name}"); Console.WriteLine($"Tossing: {Dough}"); Console.WriteLine($"Adding sauce: {Sauce}"); Console.WriteLine("Adding toppings: "); Toppings.ForEach(x => Console.WriteLine($" {x}")); } public void Bake() { Console.WriteLine("Bake for 25 minutes"); } public void Cut() { Console.WriteLine("Cutting the pizza into diagnol slices"); } public void Box() { Console.WriteLine("Placing pizza in official PizzaStore box......"); } }
}
- 各种Pizza
namespace SimpleFactory.Pizzas {
public class CheesePizza: Pizza { public CheesePizza() { Name = "Cheese Pizza"; Dough = "Think Dough"; Sauce = "Salad"; Toppings.Add("Grated Reggiano Cheese"); } }
}
namespace SimpleFactory.Pizzas {
public class ClamPizza: Pizza { public ClamPizza() { Name = "Clam Pizza"; Sauce = "Tomato sauce"; Dough = "Soft dough"; Toppings.Add("Shrimp meat"); } }
}
namespace SimpleFactory.Pizzas {
public class PepperoniPizza: Pizza { public PepperoniPizza() { Name = "Pepperoni Pizza"; Dough = "Thin dough"; Sauce = "Black pepper"; Toppings.Add("Beef Granules"); Toppings.Add("Niblet"); } }
}
- 简单工厂
using SimpleFactory.Pizzas;
namespace SimpleFactory {
public class SimplePizzaFactory { public Pizza CreatePizza(string type) { Pizza pizza = null; switch (type) { case "cheese": pizza = new CheesePizza(); break; case "pepperoni": pizza = new PepperoniPizza(); break; case "clam": pizza = new ClamPizza(); break; } return pizza; } }
}
- PizzaStore
using SimpleFactory.Pizzas;
namespace SimpleFactory {
public class PizzaStore { private readonly SimplePizzaFactory _factory; public PizzaStore(SimplePizzaFactory factory) { _factory = factory; } public Pizza OrderPizza(string type) { var pizza = _factory.CreatePizza(type); pizza.Prepare(); pizza.Bake(); pizza.Cut(); pizza.Box(); return pizza; } }
} ```
工厂方法模式
设计原则
- DIP (Dependency Inversion Principle) 依赖反转原则.
- 进一步解释就是: 高级别的组件不应该依赖于低级别的组件, 它们都应该依赖于抽线.