3. Single case design mode

Posted by lorne17 on Sat, 19 Feb 2022 18:23:36 +0100

3.1 introduction

The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance for a class in the whole software system, and the class only provides a method to obtain its object instance (static method).

3.2 eight ways of single case design mode

1) Hungry Han formula (static constant)
2) Hungry Chinese style (static code block)
3) Lazy (thread unsafe)
4) Lazy (thread safety, synchronization method)
5) Lazy (thread safe, synchronous code block)
6) Double check
7) Static inner class
8) Enumeration

3.3 hungry Han formula (static constant)

The application steps of hungry Han formula (static constant) are as follows:

  1. Constructor Privatization (prevent new)
  2. Class
  3. Expose a static public method. getInstance
  4. code implementation
//Hungry Han formula (static variable) 
class Singleton {
	//1. Privatization of constructor
	new private Singleton() {}

	//2. Create object instances within this class
	private final static Singleton instance = new Singleton();

	//3. Provide a public static method to return the instance object
	public static Singleton getInstance() { 
		return instance;
	}
}

Description of advantages and disadvantages:

  1. Advantages: this method is relatively simple, that is, the instantiation is completed when the class is loaded. Thread synchronization problems are avoided.

  2. Disadvantages: the instantiation is completed when the class is loaded, which does not achieve the effect of Lazy Loading. If you have never used this instance from beginning to end, it will cause a waste of memory

  3. This method is based on the classloder mechanism and avoids the problem of multi-threaded synchronization. However, instance is instantiated during class loading. In the singleton mode, most of them call the getInstance method, but there are many reasons for class loading. Therefore, it is uncertain that other methods (or other static methods) lead to class loading, At this time, initializing instance does not achieve the effect of lazy loading

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

3.4 hungry Chinese style (static code block)

code

//Hungry Han formula (static variable) 
class Singleton {
   //1. Privatization of constructor
   new private Singleton() {}
   
   //2. Create object instances within this class
   private	static Singleton instance;
   
   static { // In a static code block, create a singleton object
   	instance = new Singleton();
   }
   
   //3. Provide a public static method to return the instance object
   public static Singleton getInstance() {
   	return instance;
   }
}

Description of advantages and disadvantages

  1. This method is actually similar to the above method, except that the class instantiation process is placed in the static code block. When the class is loaded, the code in the static code block is executed to initialize the class instance. The advantages and disadvantages are the same as those above.
  2. Conclusion: This singleton mode is available, but it may cause a waste of memory

3.5 lazy (thread unsafe)

code

class Singleton {
	private static Singleton instance;
	private Singleton() {}

	//Provide a static public method. Create instance only when this method is used
	//Lazy style
	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 a thread enters the if (singleton == null) judgment statement block and has not had time to execute, another thread also passes the judgment statement, multiple instances will be generated. Therefore, this method cannot be used in a multithreaded environment
  3. Conclusion: do not use this method in actual development

3.6 lazy (thread safety, synchronization method)

code

// Lazy (thread safety, synchronization method) 
class Singleton {
	private static Singleton instance;

	private Singleton() {}
	
	//Provide a static public method, add synchronous processing code, and solve thread safety problems
	//Lazy style
	public static synchronized Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

Description of advantages and disadvantages:

  1. Solves the thread safety problem
  2. The efficiency is too low. When each thread wants to obtain an instance of a class, it needs to synchronize the getInstance() method. In fact, this method only executes the instantiation code once. If you want to obtain this kind of instance later, just return it directly. Method is too inefficient to synchronize
  3. Conclusion: this method is not recommended in practical development

3.7 lazy (thread safe, synchronous code block)

code

// Lazy (thread safety, synchronization method) 
class Singleton {
	private static Singleton instance;

	private Singleton() {}
	
	//Provide a static public method, add synchronous processing code, and solve thread safety problems
	//Lazy style
	public static Singleton getInstance() {
		if(instance == null) {
			synchronized(Singleton.class){
				instance = new Singleton();
			}	
		}
		return instance;
	}
}

Not recommended

3.8 double check

code

// Lazy (thread safety, synchronization method) 
class Singleton {
	private static volatile Singleton instance;
	
	private Singleton() {}
	//Provide a static public method and add double check code to solve the problem of thread safety and lazy loading
	//At the same time, it ensures the efficiency and is recommended to use
	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 concept of double check is often used in multithreading development. As shown in the code, we have conducted two if (singleton == null) checks to ensure thread safety.
  2. In this way, the instantiated code is executed only once. When accessing again later, judge if (singleton == null) and return the instantiated object directly, which also avoids repeated method synchronization
  3. Thread safety; Delayed loading; High efficiency
  4. Conclusion: this single case design mode is recommended in practical development

3.9 static internal class

code

// The static internal class is completed, which is recommended
class Singleton {
	private static volatile Singleton instance;
	//Constructor privatization
	private Singleton() {}
	//Write a static inner class with a static attribute Singleton 
	private static class SingletonInstance {
		private static final Singleton INSTANCE = new Singleton();
	}
	//Provide a static public method and directly return singletoninstance INSTANCE 
	public static synchronized Singleton getInstance() {
		return SingletonInstance.INSTANCE;
	}
}

Description of advantages and disadvantages:

  1. This method adopts the mechanism of class loading to ensure that there is only one thread when initializing the instance.
  2. The static internal class method does not instantiate the Singleton class immediately when it is loaded. Instead, when instantiation is needed, call the getInstance method to load the Singleton class, so as to complete the instantiation of 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 ensure the safety of threads. When the class is initialized, other threads cannot enter.
  4. Advantages: thread insecurity is avoided, delayed loading is realized by using the characteristics of static internal classes, and the efficiency is high
  5. Conclusion: recommended

3.10 enumeration

code

//Using enumeration, you can realize singleton, which is recommended
enum Singleton {
	INSTANCE; //attribute
	public void sayOK() {
		System.out.println("ok~");
	}
}

Description of advantages and disadvantages:

  1. With jdk1 5 to implement the singleton mode. It can not only avoid the problem of multi-threaded synchronization, but also prevent deserialization and re creation of new objects.
  2. This approach is advocated by Josh Bloch, author of Effective Java
  3. Conclusion: it is recommended to use

3.12 notes and details of singleton mode

  1. The singleton mode ensures that there is only one object in the system memory, which saves system resources. For some objects that need to be created and destroyed frequently, the singleton mode can improve the system performance
  2. When you want to instantiate a singleton class, you must remember to use the corresponding method to get the object instead of new
  3. Scenarios for using singleton mode: objects that need to be created and destroyed frequently, objects that take too much time or resources to create objects (i.e. heavyweight objects), but are often used, tool objects, and objects that frequently access databases or files (such as data sources, session factories, etc.)

Topics: Java Design Pattern