個人封裝的C#單例基類


 /// <summary>
    /// 帶接口的單例,通常用於可MOCK的類
    /// </summary>
    /// <typeparam name="T">單例的類型</typeparam>
    /// <typeparam name="I">單例類型的接口</typeparam>
    public class SingleInstance<T, I> where T : I
    {
        private static object lockObj = new object();
        private static T mySelf = default(T);
        public static I Instance
        {
            get
            {
#if DEBUG
                if (Mocking != null)
                    return Mocking;
#endif
                lock (lockObj)
                {
                    if (mySelf == null)
                    {
                        mySelf = InstanceCreater.CreateInstance<T>();
                    }
                }

                return mySelf;
            }
        }

#if DEBUG
        public static I Mocking { get; set; }
#endif

    }

    /// <summary>
    /// 單例,需要在當前類中定義
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SingleInstance<T> where T : class
    {
        private static object lockObj = new object();
        private static T mySelf;//= default(T);
        public static T Instance
        {
            get
            {
                lock (lockObj)
                {
                    if (mySelf == null)
                    {
                        mySelf = InstanceCreater.CreateInstance<T>();
                    }
                }

                return mySelf;
            }
        }
#if MOCK
        public static void InstanceClear()
        {
           mySelf=null;
        } 
#endif
    } 

    static class InstanceCreater
    {
        public static T CreateInstance<T>()
        {
            var type = typeof(T);
            try
            {
                return (T)type.Assembly.CreateInstance(type.FullName, true, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null, null);
            }
            catch (MissingMethodException ex)
            {
                throw new System.Exception(string.Format("{0}(單例模式下,構造函數必須為private)", ex.Message));
            }
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM