工廠模式定義:實例化對象,用工廠方法代替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(); } }