02_简单工厂模式
简单工厂模式(Simple Factory Pattern)是一种创建型设计模式,属于工厂模式的一种。在简单工厂模式中,通过一个工厂类来负责创建对象实例,而客户端无需直接创建对象,只需要通过工厂类来获取所需的对象。
简单工厂模式包含以下几个角色:
- 工厂类(Factory):负责创建对象实例的类。
- 产品类(Product):工厂类所创建的对象实例的共同接口或父类。
- 具体产品类(Concrete Product):实现产品类接口的具体对象类。
Product:
public interface IFruit { /// <summary> /// 水果的数量 /// </summary> double Amount { get; } /// <summary> /// 种植 /// </summary> /// <param name="amount"></param> void Plant(int amount); /// <summary> /// 生成 /// </summary> /// <param name="days"></param> void Grow(int days); /// <summary> /// 收获 /// </summary> /// <returns></returns> double Harvest(); }
Concrete Product
苹果
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Apple : IFruit { public double Amount { get; private set; } public void Grow(int days) { Amount *= days * 0.85; } public double Harvest() { return Amount; } public void Plant(int amount) { Amount = amount; } }
香蕉
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Banana : IFruit { public double Amount { get; private set; } public void Grow(int days) { Amount *= days * 2; } public double Harvest() { return Amount; } public void Plant(int amount) { Amount = amount; } }
橘子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Orange : IFruit { public double Amount { get; private set; } public void Grow(int days) { Amount *= days * 1.5; } public double Harvest() { return Amount; } public void Plant(int amount) { Amount = amount; } }
Factory
public class FruitFactory { public static IFruit Create(string name) { switch (name) { case "Apple": return new Apple(); case "Banana": return new Banana(); case "Orange": return new Orange(); default: return null; } }
//通过反射获取对象实例 public static IFruit Create<T>() { return (IFruit)Activator.CreateInstance(typeof(T)); } }
static void Main(string[] args) { var apple = FruitFactory.Create("Apple"); var banana = FruitFactory.Create("Banana"); var orange = FruitFactory.Create("Orange"); apple = FruitFactory.Create<Apple>(); banana = FruitFactory.Create<Banana>(); orange = FruitFactory.Create<Orange>(); apple.Plant(10); apple.Grow(180); Console.WriteLine($"苹果收获:{apple.Harvest()}") ; banana.Plant(10); banana.Grow(180); Console.WriteLine($"香蕉收获:{banana.Harvest()}"); orange.Plant(10); orange.Grow(180); Console.WriteLine($"柑橘收获:{orange.Harvest()}"); Console.ReadKey(); }