類實例時只實例一次或者在調用實例的時候只執行一次

Singleton模式:
using System;
public class Singleton
{
        private static Singleton instance;
        private Singleton() {}
        public static Singleton Instance
        {
            get
                {
                        if (instance == null)
                        {
                        instance = new Singleton();
                        }
                        return instance;
                 }
        }
}spa


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++get

//==========================================================class

也能夠選擇在調用的時候才實例化的

public class sealed Singleton
{
        private static volatile Singleton _instance;
        private static object syncRoot = new object();
        private Singleton() { }
        public Singleton Instance
        {
            get
            {
                    if(_instance == null)
                    {
                        Lock(syncRoot)
                        {
                            if(_instance == null)
                            {
                                _instance = new Singleton();
                            }
                        }
                        }
                    return _instance;
                }
            }
}
object

相關文章
相關標籤/搜索