using System; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //需要什么食物,创建什么工厂 FactoryCreate _factorycreate = new YaJiaFactoryCreate(); Food _food = _factorycreate.Create(); _food.MakeFood(); //反射机制 选择实例化的类型 FactoryCreate _factorycreate2; _factorycreate2 = (FactoryCreate)Assembly.Load("ConsoleApplication1").CreateInstance("ConsoleApplication1." + "YaBoFactoryCreate"); Food _food2 = _factorycreate2.Create(); _food2.MakeFood(); } } /// <summary> /// 食物接口或抽象类 /// </summary> public abstract class Food { /// <summary> /// 生产食物 /// </summary> public abstract void MakeFood(); } /// <summary> /// 工厂接口或抽象类 /// </summary> public abstract class FactoryCreate { public abstract Food Create(); } /// <summary> /// 鸭脖工厂 /// </summary> public class YaBoFactoryCreate : FactoryCreate { public override Food Create() { return new YaBo(); } } /// <summary> /// 鸭架工厂 /// </summary> public class YaJiaFactoryCreate : FactoryCreate { public override Food Create() { return new YaJia(); } } /// <summary> /// 生产鸭脖 /// </summary> public class YaBo : Food { public override void MakeFood() { Console.WriteLine("鸭脖"); Console.ReadLine(); } } /// <summary> /// 生产鸭架 /// </summary> public class YaJia : Food { public override void MakeFood() { Console.WriteLine("鸭架"); Console.ReadLine(); } } }