使用的类
//公共方法抽象成接口 public interface ISms { void Send(); } public class ALiSms : ISms { public void Send() { Console.WriteLine("阿里"); } } public class XMSMSms : ISms { public void Send() { Console.WriteLine("XMSM"); } }
工厂类
public class SMSFactory<T> where T :class { static ICreate creator; //接口 interface ICreate { T Create(); } //创建对象的类 class Creater<U> : ICreate where U : T,new() { /// <summary> /// 创建对应类的方法 /// </summary> /// <returns></returns> public T Create() { return new U(); } } class SingleCreator<U> : ICreate where U : T, new() { #region 单例模式方法1:双旋锁 //T instance; //object locker = new object(); //public T Create() //{ // if (instance == null) // { // lock (locker) // { // if (instance == null) // { // Interlocked.Exchange(ref instance, new U()); // } // } // } // return instance; //} #endregion #region 第二种:利用静态只读,只有访问这个类时,才会被创建 class SingleClass { public static readonly T instance = new U(); } public T Create() { return SingleClass.instance; } #endregion } #region 无参数方法 /// <summary> /// 对外创建对象的函数 /// </summary> /// <returns></returns> public static T CreateSms() { return creator.Create(); } /// <summary> /// 初始化对象创建类的方法 /// </summary> /// <typeparam name="S">传入的的泛型S应继承自T并且可实例化</typeparam> public static void InitSms<S>() where S : T, new() { creator = new Creater<S>(); } /// <summary> /// 初始化对象创建类的单例方法 /// </summary> /// <typeparam name="S">传入的的泛型S应继承自T并且可实例化</typeparam> public static void InitSingleSms<S>() where S : T, new() { creator = new SingleCreator<S>(); } #endregion #region 有参数方法 static IDictionary<string, ICreate> dictCreate = new System.Collections.Concurrent.ConcurrentDictionary<string, ICreate>(); public static T CreateSms(string key) { ICreate create; if (dictCreate.TryGetValue(key, out create)) { return create.Create(); } throw new Exception("未注册"); } public static void InitSms<S>(string key) where S : T, new() { dictCreate[key] = new Creater<S>(); } public static void InitSingleSms<S>(string key) where S : T, new() { dictCreate[key] = new SingleCreator<S>(); } #endregion }
调用
SMSFactory<ISms>.InitSms<ALiSms>("ali"); SMSFactory<ISms>.InitSingleSms<XMSMSms>("xmsm"); SMSFactory<ISms>.InitSingleSms<FriendSms>("friend"); var s1 = SMSFactory<ISms>.CreateSms("ali"); s1.Send(); var s2 = SMSFactory<ISms>.CreateSms("xmsm"); s2.Send(); var s3 = SMSFactory<ISms>.CreateSms("friend"); s3.Send();