HeadFirst (5) Singleton single-piece design pattern

 

Single Piece Design Pattern:

Make sure there is only one instance of a class and provide a global access point

1 static variable

1 private constructor

1 static method

 

Used to manage shared resources, such as: thread pools, database connections, etc.

 

There are some objects we only need one, such as:

Thread pool threadpool, cache cache, database connection connection, registry registry, etc.

 

 

We must assume that all programs are multithreaded

Synchronization of shared resources under multi-threading is very critical

 

 

If the performance of getInstance() is not critical to the application, lock the method directly

Synchronizing a method may cause the execution efficiency of the program to drop by 100 times,

If you use the getInstance() program in a frequently run place, you may have to reconsider!

 

package lazy;

public class Singleton {

	//Instantiate only when used
	private static Singleton uniqueInstance = null;
	
	private Singleton() {}
	
	/**
	 * Synchronized method, no two threads can enter this method at the same time
	 */
	public static synchronized Singleton getInstance() {
		if(uniqueInstance==null) {
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}
	
}

 

 

Use "eager" instance creation instead of lazy instantiation

 

public class Singleton {
	
	//Create the object directly to ensure thread-safety
	private static Singleton unqueInstance = new Singleton();
	
	//constructor private
	private Singleton() {}
	
	//Provide global access point
	public static Singleton getInstance() {
		return unqueInstance;
	}
}

 

 

Use "double-checked locking" to reduce the use of synchronization in getInstance()

package lazy;

public class Singleton {

	//Instantiate only when used
	private static Singleton uniqueInstance = null;
	
	private Singleton() {}
	
	/**
	 * Use double-checked locking to ensure that multi-threaded environments are not problematic
	 */
	public static Singleton getInstance() {
		if(uniqueInstance==null) {
			synchronized(Singleton.class) {
				if(uniqueInstance==null) {
					uniqueInstance = new Singleton();
				}
			}
		}
		return uniqueInstance;
	}
	
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326693334&siteId=291194637