[C#-Design Pattern] Singleton

[C#-Design Pattern] Singleton

參考: http://weiyiao.pixnet.net/blog/post/30971305-%5Bc%23%5D-%5Bdesign-patterns%5D-singleton-pattern

ex 1: 利用了一個 Mutex 的物件,透過 lock 的方式,讓第一個執行序可以安全的建立實體,後續的執行序可以等候實體建立完成,可以避免互相打架的方式:


    {
        private static readonly object Mutex = new object();
        private static volatile Singleton _instance;

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Mutex)
                    {
                        if (_instance == null)
                            _instance = new Singleton();
                    }
                }
                return _instance;
            }
        }
    }

ex 2: 限制參數 (ftpUrl…) 儲存只能一次


    {
        private static readonly object mutex = new object();
        private static volatile FtpProperies instance;
        private string ftpUrl;
        private string ftpUserName;
        private string ftpPassword;

        private FtpProperies() { }

        private static FtpProperies GetInstance()
        {
            if (instance == null)
            {
                lock (mutex)
                {
                    if (instance == null)
                        instance = new FtpProperies();
                }
            }
            return instance;
        }

        public static void SetFtpProperies(string ftpUrl, string ftpUserName, string ftpPassword)
        {
            if (instance == null || instance.ftpUrl == null)
            {
                GetInstance().ftpUrl = ftpUrl; 
            }

            if (instance == null || instance.ftpUserName == null)
            {
                GetInstance().ftpUserName = ftpUserName;
            }

            if (instance == null || instance.ftpPassword == null)
            {
                GetInstance().ftpPassword = ftpPassword;
            }
        }

        public static string GetFtpUrl()
        {
            return instance.ftpUrl;
        }

        public static string GetUserName()
        {
            return instance.ftpUserName;
        }

        public static string GetPassword()
        {
            return instance.ftpPassword;
        }
    }