Singleton mode (lazy and hungry)-only child is good

  Singleton mode (Singleton) : Ensure that a class has only one instance, and provide a global access point to access it.

  Features :

  • A singleton class can only have one instance.
  • The singleton class must create its own unique instance.
  • The singleton class must provide this instance to all other objects.

  The difference between a lazy man and a hungry man :

  • The hungry man means that once the class is loaded, the singleton is initialized to ensure that the singleton already exists when getInstance;

  • Lazy people are lazy, and only go back to initialize this singleton when getInstance is called.

  • The hungry man is inherently thread-safe and can be directly used for multi-threading without problems;

  • The lazy style itself is not thread-safe. In order to achieve thread safety, there are double locks and,


Lazy singleton

  Method 1: Synchronized() double lock

    class Singleton
    {
    
    
        private static Singleton instance;
        private static readonly object syncRoot = new object();//只读

        //构造方法private,规避了外界利用new创建此类的可能
        private Singleton()
        {
    
     }

        //此方法是获得本类实例的唯一全局访问点
        public static Singleton GetInstance()
        {
    
    
        	if (instance == null)	//第一次判断是否已创建实例
        	{
    
    
        		//没有就让一条线程进入并加锁,其它线程等待,等第一条出去以后解锁,然后下一条线程再进入并加锁,直到所有线程处理完毕。
        		lock (syncRoot)		
        		{
    
    
		            if (instance == null)   //二次判断是否已创建实例
		            {
    
    
		                instance = new Singleton(); //若没有就创建一个
		            }
		        }
            }
            return instance;//否则返回已有的实例
        }
    }

  Method 2: Synchronized() method

//Synchronized在指定的对象周围创建线程安全(同步)包装,每次执行都要同步
//无论是读和写,都要一个进行完在进行下一个
public static synchronized Singleton getInstance() 
{
    
    
    if (instance == null) 
    {
    
      
        instance = new Singleton();
     }  
     return instance;
}

  Method 3: Static class : I don’t understand this yet, so I’ll keep it here for now

public class Singleton {
    
      
    private static class LazyHolder {
    
      
       private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){
    
    }  
    public static final Singleton getInstance() {
    
      
       return LazyHolder.INSTANCE;  
    }  
} 

Hungry singleton

Instantiate objects as soon as the class is loaded, occupying system resources in advance

//密封类阻止了继承,杜绝继承会增加实例的可能
public sealed class Singleton
{
    
    
	//在第一次引用类的任何成员时创建实例
	private static readonly Singleton instance = new Singleton();
	private Singleton()//构造方法私有
	{
    
    }
	public static Singleton GetInstance()
	{
    
    
		return instance;
	}
}

Guess you like

Origin blog.csdn.net/CharmaineXia/article/details/110916053