1. Singleton mode of design mode

 1. Singleton mode of design mode

table of Contents

 1. Singleton mode of design mode

 0. Introduction to singleton design pattern

1. Eight ways of singleton design pattern

1.1, hungry Chinese style (static constant)

1.2. Hungry Chinese style (static code block)

1.3, lazy man (thread unsafe)

1.4, lazy man (thread safety, synchronization method)

1.5, lazy (thread insecure, synchronized code blocks)

1.6, double check

1.7, static inner class

1.8, enumeration

Second, the use of singleton mode in jdk

Three, singleton mode notes and details


 0. Introduction to singleton design pattern

The so-called singleton design pattern of a class is to take a certain method to ensure that in the entire software system, there can only be one object instance for a certain class , and the class only provides a method (static method) to obtain its object instance.
For example, Hibernate's SessionFactory, which acts as a proxy for data storage sources and is responsible for creating Session objects. SessionFactory is not lightweight. Under normal circumstances, a project usually only needs one SessionFactory. This is the singleton mode.

1. Eight ways of singleton design pattern

  1. Hungry Chinese (static constant)
  2.  Hungry Chinese (static code block)
  3.  Lazy (unsafe thread)
  4.  Lazy (thread-safe, synchronous method)
  5.  Lazy (thread-safe, synchronized code blocks)
  6.  Double check
  7.  Static inner class
  8.  enumerate

1.1, hungry Chinese style (static constant)



//饿汉式(静态变量)

class Singleton {
	
	//1. 构造器私有化, 外部能new
	private Singleton() {
		
	}
	
	//2.本类内部创建对象实例
	private final static Singleton instance = new Singleton();
	
	//3. 提供一个公有的静态方法,返回实例对象
	public static Singleton getInstance() {
		return instance;
	}
	
}

Description of advantages and disadvantages:

1) Advantages: This writing method is relatively simple, that is, the instantiation is completed when the class is loaded. Avoid thread synchronization problems.

2) Disadvantages: The instantiation is completed when the class is loaded, which does not achieve the effect of Lazy Loading. If this instance has never been used from start to finish, it will cause a waste of memory

3) This method is based on the classloder mechanism to avoid the problem of multi-thread synchronization. However, the instance is instantiated when the class is loaded. In the singleton mode, the getInstance method is mostly called, but there are many reasons for class loading. Therefore, it is not certain that there are other ways (or other static methods) that cause the class to be loaded. At this time, initializing the instance does not achieve the effect of lazy loading

4) Conclusion: This singleton mode is available, which may cause a waste of memory

1.2. Hungry Chinese style (static code block)

//饿汉式(静态变量)

class Singleton {
	
	//1. 构造器私有化, 外部能new
	private Singleton() {
		
	}
	

	//2.本类内部创建对象实例
	private  static Singleton instance;
	
	static { // 在静态代码块中,创建单例对象
		instance = new Singleton();
	}
	
	//3. 提供一个公有的静态方法,返回实例对象
	public static Singleton getInstance() {
		return instance;
	}
	
}

Description of advantages and disadvantages:

1) This method is similar to the above method, except that the process of class instantiation is placed in a static code block. When the class is loaded, the code in the static code block is executed to initialize the instance of the class. The advantages and disadvantages are the same as above.

2) Conclusion: This singleton mode is available, but it may cause a waste of memory

1.3, lazy man (thread unsafe)

class Singleton {
	private static Singleton instance;
	
	private Singleton() {}
	
	//提供一个静态的公有方法,当使用到该方法时,才去创建 instance
	//即懒汉式
	public static Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

Description of advantages and disadvantages:

1) It has the effect of Lazy Loading, but it can only be used under single thread.

2) If in multi-threading, one thread enters the if (singleton == null) judgment statement block, and there is no time to execute it in the future, and another thread also passes the judgment statement, then multiple instances will be generated. Therefore, this method cannot be used in a multi-threaded environment

3) Conclusion: Do not use this method in actual development.

1.4, lazy man (thread safety, synchronization method)

// 懒汉式(线程安全,同步方法)
class Singleton {
	private static Singleton instance;
	
	private Singleton() {}
	
	//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
	//即懒汉式
	public static synchronized Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

Description of advantages and disadvantages:

1) Solve the problem of thread insecurity

2) The efficiency is too low. When each thread wants to obtain an instance of the class, the execution of the getInstance() method must be synchronized. In fact, this method is enough to execute the instantiation code only once. If you want to obtain an instance of this class later, just return directly. The method is too inefficient for synchronization

3) Conclusion: In actual development, this method is not recommended

1.5, lazy (thread insecure, synchronized code blocks)

// 懒汉式(线程安全,同步方法)
class Singleton {
	private static Singleton instance;
	
	private Singleton() {}
	
	//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
	//即懒汉式
	public static Singleton getInstance() {
		if(instance == null) {
            synchronized(Singleton.class){
			instance = new Singleton();
                }
		}
		return instance;
	}
}

Description of advantages and disadvantages:

1) This method is intended to improve the fourth implementation method, because the efficiency of the previous synchronization method is too low, so the instantiated code block is generated synchronously.

2) But this kind of synchronization does not play the role of thread synchronization . Consistent with the situation encountered in the third implementation method, if a thread enters the if (singleton == null) judgment statement block, and there is no time to execute it in the future, another thread also passes the judgment statement, then it will be generated Multiple instances

3) Conclusion: In actual development, this method cannot be used

1.6, double check

// 懒汉式(线程安全,同步方法)
class Singleton {
	private static volatile Singleton instance;
	
	private Singleton() {}
	
	//提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
	//同时保证了效率, 推荐使用
	
	public static synchronized Singleton getInstance() {
		if(instance == null) {
			synchronized (Singleton.class) {
				if(instance == null) {
					instance = new Singleton();
				}
			}
			
		}
		return instance;
	}
}

Description of advantages and disadvantages:

1) The Double-Check concept is often used in multi-threaded development. As shown in the code, we have performed two if (singleton == null) checks to ensure thread safety.

2) In this way, the instantiation code only needs to be executed once, and when it is accessed again later, it will judge if (singleton == null) and directly return the instantiated object, which also avoids repeated method synchronization.

3) Thread safety; lazy loading; higher efficiency

4) Conclusion: In actual development, it is recommended to use this singleton design pattern

1.7, static inner class

class Singleton {
	private static volatile Singleton instance;
	
	//构造器私有化
	private Singleton() {}
	
	//写一个静态内部类,该类中有一个静态属性 Singleton
	private static class SingletonInstance {
		private static final Singleton INSTANCE = new Singleton(); 
	}
	
	//提供一个静态的公有方法,直接返回SingletonInstance.INSTANCE
	
	public static synchronized Singleton getInstance() {
		
		return SingletonInstance.INSTANCE;
	}
}

Description of advantages and disadvantages:

1) This method uses a class loading mechanism to ensure that there is only one thread when initializing an instance.

2) The static internal class method will not be instantiated when the Singleton class is loaded, but when instantiation is needed, the getInstance method will be called to load the SingletonInstance class, thus completing the instantiation of the Singleton.

3) The static properties of the class will only be initialized when the class is loaded for the first time, so here, the JVM helps us to ensure the safety of the thread. When the class is initialized, other threads cannot enter.

4) Advantages: avoid thread insecurity, use static internal class characteristics to achieve lazy loading, high efficiency

5) Conclusion: Recommended.

1.8, enumeration

//使用枚举,可以实现单例, 推荐
enum Singleton {
	INSTANCE; //属性
	public void sayOK() {
		System.out.println("ok~");
	}
}

Description of advantages and disadvantages:

1) This uses the enumeration added in JDK1.5 to implement the singleton mode. Not only can avoid multi-thread synchronization problems, but also prevent deserialization from re-creating new objects.

2) This method is advocated by Effective Java author Josh Bloch

3) Conclusion: recommended

Second, the use of singleton mode in jdk

1) In our JDK, java.lang.Runtime is the classic singleton mode (hungry Chinese style)

2) Code analysis + Debug source code + code description

Three, singleton mode notes and details

1) The singleton mode ensures that there is only one object of this class in the system memory, which saves system resources. For some objects that need to be created and destroyed frequently, the singleton mode can improve system performance

2) When you want to instantiate a singleton class, you must remember to use the corresponding method of obtaining the object instead of using new

3) Scenarios used in singleton mode: objects that need to be created and destroyed frequently, too much time or resources are consumed when creating objects (ie: heavyweight objects), but frequently used objects and tool objects , Objects that frequently access databases or files (such as data sources, session factories, etc.)

Guess you like

Origin blog.csdn.net/qq_45072383/article/details/114004431