(2)简单工厂
我们先看下类图:
1.建立工厂类FruitFactory:这里有两种写,一种通过Switch,一种通过反射

1 using System.Xml.Linq; 2 using System; 3 4 namespace 简单工厂 5 { 6 internal class FruitFactory 7 { 8 public static IFruit Create(string name) 9 { 10 switch (name) 11 { 12 case "Apple": 13 return new Apple(); 14 case "Banana": 15 return new Banana(); 16 case "Orange": 17 return new Orange(); 18 19 ///如果要新加一种水果则要修改此处的代码会违背开闭原则 20 default: 21 return null; 22 } 23 } 24 25 26 /// <summary> 27 /// 利用反射 28 /// </summary> 29 /// <typeparam name="T"></typeparam> 30 /// <returns></returns> 31 public static IFruit Create<T>() 32 { 33 return (IFruit)Activator.CreateInstance(typeof(T)); 34 } 35 } 36 }
2.建立接口IFruit:

1 namespace 简单工厂 2 { 3 public interface IFruit 4 { 5 /// <summary> 6 /// 水果的单价 7 /// </summary> 8 double Amount { get; } 9 10 11 /// <summary> 12 /// 种的数量 13 /// </summary> 14 /// <param name="amount"></param> 15 void Plant(int amount); 16 17 /// <summary> 18 /// 生成 19 /// </summary> 20 /// <param name="days"></param> 21 void Grow(int days); 22 23 /// <summary> 24 ///收获 25 /// </summary> 26 /// <returns></returns> 27 double Harvest () ; 28 } 29 }
2.建立实现类Apple:

1 namespace 简单工厂 2 { 3 public class Apple : IFruit 4 { 5 public double Amount { get; set; } 6 7 public void Grow(int days) 8 { 9 Amount *= days * 0.65; 10 } 11 12 public double Harvest() 13 { 14 return Amount; 15 } 16 17 public void Plant(int amount) 18 { 19 Amount = amount; 20 } 21 } 22 }
3.建立实现类Banana:

1 namespace 简单工厂 2 { 3 public class Banana : IFruit 4 { 5 public double Amount { get; set; } 6 7 public void Grow(int days) 8 { 9 Amount *= days * 1.2; 10 } 11 12 public double Harvest() 13 { 14 return Amount; 15 } 16 17 public void Plant(int amount) 18 { 19 Amount = amount; 20 } 21 } 22 }
4.建立实现类Orange:

1 namespace 简单工厂 2 { 3 public class Orange : IFruit 4 { 5 public double Amount { get; set; } 6 7 public void Grow(int days) 8 { 9 Amount *= days * 0.85; 10 } 11 12 public double Harvest() 13 { 14 return Amount; 15 } 16 17 public void Plant(int amount) 18 { 19 Amount = amount; 20 } 21 } 22 }
5:调用:

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 简单工厂 8 { 9 internal class Program 10 { 11 static void Main(string[] args) 12 { 13 var apple = FruitFactory.Create("Apple"); 14 var orange = FruitFactory.Create("Orange"); 15 var banana = FruitFactory.Create<Banana>(); 16 17 apple.Plant(10); 18 apple.Grow(180); 19 Console.WriteLine($"苹果收获: {apple.Harvest()}"); 20 21 banana.Plant(10); 22 banana.Grow(180); 23 Console.WriteLine($"香蕉收获: {banana.Harvest()}"); 24 25 orange.Plant(10); 26 orange.Grow(180); 27 Console.WriteLine($"柑橘收获: {orange.Harvest()}"); 28 29 Console.ReadKey(); 30 } 31 } 32 }
该模式中的问题,是如果要新加一种水果则要修工厂的代码会违背开闭原则,我们后面用抽象工厂方法将解决这个问题.