About the singleton pattern

单例模式是为了使一个类只有一个实例,并提供一个全局访问点--抄的

 public class SingleInstance<T> where T:class,new()
    {
        private static T _instance;
        private static readonly object lock= new object();

        public static T getInstance()
        {
            if (_instance == null)
            {
                lock (lock)
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                    }
                    
                }
            }
            return _instance;
        }
    }

The first if is to synchronize access without needing to lock every time, wasting resources;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325324207&siteId=291194637