工厂模式定义:实例化对象,用工厂方法代替new操作。
接口(IBase):
public interface IBase { void Excute(); }
实现类A(BaseAImpl):
public class BaseAImpl : IBase { public void Excute() { Type type = this.GetType(); Console.WriteLine("类全A名称:{0},类名:{1},是否实现接口IBase:{2}", type.FullName, type.Name, typeof(IBase).IsAssignableFrom(type)); } }
实现类B(BaseBImpl):
public class BaseBImpl : IBase { public void Excute() { Type type = this.GetType(); Console.WriteLine("类B全名称:{0},类名:{1},是否实现接口IBase:{2}", type.FullName, type.Name, typeof(IBase).IsAssignableFrom(type)); } }
类C(BaseC):(特殊类,用于区别)
public class BaseC { public void Excute() { Type type = this.GetType(); Console.WriteLine("类全A名称:{0},类名:{1},是否实现接口IBase:{2}", type.FullName, type.Name, typeof(IBase).IsAssignableFrom(type)); } }
工厂类(Factory):
/// <summary> /// 工厂类 /// </summary> public class Factory { /// <summary> /// 工厂方法(创建实例的地方,需要什么拿什么) /// </summary> /// <param name="fullName">类型全名称</param> /// <returns>实现IBase的实例对象</returns> public IBase CreateBase(string fullName) { // 获取程序集里面的所有类型 Type[] types = this.GetType().Assembly.GetTypes(); // 遍历所有类型,查找 foreach (Type type in types) { // 判断类型全名称和是否实现IBase接口 if (type.FullName == fullName && typeof(IBase).IsAssignableFrom(type)) return Activator.CreateInstance(type) as IBase; } return null; } }
演示结果:
class Program { static void Main(string[] args) { Factory factory = new Factory(); IBase instanceA= factory.CreateBase(typeof(BaseAImpl).FullName); IBase instanceB = factory.CreateBase(typeof(BaseBImpl).FullName); IBase instanceC = factory.CreateBase(typeof(BaseC).FullName); // 特殊例子,用于区别 instanceA.Excute(); instanceB.Excute(); if (instanceC == null) { Console.WriteLine("类C:{0}未实现接口IBase", typeof(BaseC).FullName); } Console.ReadLine(); } }