工厂模式有四个角色:抽象工厂,具体工厂,抽象产品,具体产品
1.抽象工厂
namespace 验证工厂模式 { public abstract class AbstractCarFactory { public abstract Car CreateCarInstance(); } }
2.具体工厂
namespace 验证工厂模式 { using System.Reflection; public class BenzCarFactory:AbstractCarFactory { public override Car CreateCarInstance() { return new BenzCar(); } } } namespace 验证工厂模式 { public class HavarCarFactory:AbstractCarFactory { public override Car CreateCarInstance() { return new HavarCar(); } } }
3.抽象产品
namespace 验证工厂模式 { public abstract class Car { public abstract void MingDi(); } }
4.具体产品
namespace 验证工厂模式 { class BenzCar:Car { public override void MingDi() { Console.WriteLine("奔驰车,嗡嗡"); } } } namespace 验证工厂模式 { class HavarCar:Car { public override void MingDi() { Console.WriteLine("哈佛H6,滴滴"); } } }
5.具体实现
public class Program { static void Main(string[] args) { AbstractCarFactory factory=new BenzCarFactory(); Car car=factory.CreateCarInstance(); car.MingDi(); //反射加载类【Load函数的参数时程序集名,createInstance的参数是 "命名空间."+"类名"】 AbstractCarFactory factory2 = (HavarCarFactory)Assembly.Load("验证工厂模式").CreateInstance("验证工厂模式.HavarCarFactory"); Car car2=factory2.CreateCarInstance(); car2.MingDi(); Console.ReadKey(); } }