Shredded singleton design pattern (detailed analysis)

Foreword

Singleton instance of the object is mainly used to ensure that the system of a class of uniqueness, is the simplest design pattern, but in the interview also often asked, is well worth us to learn. If you encounter interview investigate what design patterns are also welcome message, I will promptly send new blog post.

1. schema definition

Singleton pattern (the Singleton the Pattern) : to ensure that only one instance of a certain class, and the like and to instantiate the system provides to this example, the class is called singleton, it will provide a method of global access. Singleton pattern is an object to create the schema.

Singleton pattern three points:

  • Only one instance of a class
  • We must create the instance itself
  • Self provide this example the entire system

2. Mode realization

To achieve Singleton pattern, we can start from its three main points:

The first is the uniqueness of a single case, since a single case is unique , there is no doubt that we should give him add statickeywords, and because this object should not be exposed to direct, so plus privateaccess limited.

private static Singleton instince = null;

Next, is the object needs to create a singleton class itself , then we should be shielded interface to the outside world access the class initialization method, that is, with the privatemodified constructor.

private Singleton() {
}

Finally it is relatively easy to implement, and to the public factory method statickeyword, you can achieve this instance to provide the entire system.

public static Singleton getInstance() {
	if (instance == null) {
		instince = new Singleton();
	}
	return instance;
}

The above code all together, and you can get the code follows the singleton pattern implementation templates:

public class Singleton {
	//静态私有成员变量,保证实例的唯一性
	private static Singleton instince = null;
	//私有构造函数,保证实例由类自行创建
	private Singleton() {
	}
	// 静态公有工厂方法,向系统提供这个唯一实例
	public static Singleton getInstance() {
		if (instance == null) {
			instince = new Singleton();
		}
		return instance;
	}
}

Here is the template for the above singleton client test code:

public Client {
	public static void main(String []args) {
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();
		System.out.println(s1 == s2); //true
	}
}

Example 3. Single mode expansion

Examples can be divided into single-mode idler single embodiment and starving single embodiment , they differ primarily on the class object initialization time in a single embodiment . Let us explain in detail:

3.1 Example lazy single

Figure lazy structural formula Singleton pattern as shown below:
Here Insert Picture Description
In the model diagram, we can see that this instance of the object is not initialized when the class is created, but until someone calls the getInstance()initialize method to obtain an instance of an object when it is instantiated it is precisely this reflects the lazy man's "laziness."

Example The following is the code lazy single "class ID number" as an example, prepared.

public class IdentityCardNo {
	private String no;
	
	//某个类只能有一个实例
	private static IdentityCardNo instince = null;
	
	//必须自行创建这个实例
	private IdentityCardNo() {
		
	}
	
	//必须自行向整个系统提供这个实例
	public static IdentityCardNo getInstance() {
		if (instince == null) {
			System.out.println("第一次办理身份证,分配新号码");
			instince = new IdentityCardNo();
			instince.setIdentityCardNo("400000199710301111");
		} else {
			System.out.println("重复办理身份证,获取旧号码");
		}
		return instince;
	}
	public String getIdentityCardNo() {
		return no;
	}

	public void setIdentityCardNo(String no) {
		this.no = no;
	}
}

The above method may be counterfeit, wrote a Client class to be tested.

Example 3.2 starving single

Structure Example FIG starving single mode as shown below:
Here Insert Picture Description
As the "hunger" starving properties single embodiment, so that it is based on the loading stage singleton class object has been initialized , we can see from the above structure of FIG. out of this.

The following codes are starving achieve the above example of formula:

public class IdentityCardNo {
	private String no;
	
	//某个类只能有一个实例
	private static IdentityCardNo instince = new IdentityCardNo();
	
	//必须自行创建这个实例
	private IdentityCardNo() {
		System.out.println("第一次办理身份证,分配新号码");
	}
	
	//必须自行向整个系统提供这个实例
	public static IdentityCardNo getInstance() {
		instince.setIdentityCardNo("400000199710301111");
		return instince;
	}
	public String getIdentityCardNo() {
		return no;
	}

	public void setIdentityCardNo(String no) {
		this.no = no;
	}
}

4. The multi-threaded environment singleton

Lazy single cases mentioned above is not thread-safe, in a multithreaded environment, the uniqueness of the object can not be guaranteed . So there are several single-thread safe following embodiment mode implemented method, wherein the first and second type method is a lazy improvement is an improvement of the third type hungry man.

4.1 Load Delay

We can use synchronizedthe keyword modification getInstance()methods, use patterns delay loading ensure the uniqueness of the object in a multithreaded environment. However, this approach is likely to cause congestion thread, efficiency is not high.

Codes are as follows:

public class Singleton {
	private static Singleton instince = null;
	private Singleton() {
	}
	public static synchronized Singleton getInstance() {
		if (instance == null) {
			instince = new Singleton();
		}
		return instance;
	}
}

4.2 double checking locks

In this way a dual locking mechanism, and the thread-safe in a multithreaded situation can maintain high performance, it is more recommended method to use.

Codes are as follows:

public class Singleton {
	private static Singleton instince = null;
	private Singleton() {
	}
	public static Singleton getInstance() {
		if (instance == null) {
			//只将synchronized关键字用在了初始化模块
			synchronized (Singleton.class) {
				if (install == null) {
					instince = new Singleton();
				}
			}
		}
		return instance;
	}
}

4.3 static inner classes

This way to the object by adding finalkeywords modification can achieve the same effect double check the lock mode , but the implementation is simpler. Initialization of the static field using a delay, this mode should be used instead of double lock detection mode. This embodiment applies only to the static field, the double lock detection mode can be used when a delay required to initialize instance fields.

Codes are as follows:

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

Reference material

  1. Singleton | newbie tutorial
  2. "Java design patterns"
  3. Java implementation Singleton | CSDN
Published 89 original articles · won praise 633 · Views 650,000 +

Guess you like

Origin blog.csdn.net/weixin_42292229/article/details/105286188