Design Patterns - Singleton Pattern (Lazy Man Pattern)

http://794950040.iteye.com/blog/2208102
is based on the implementation of the above hungry model

/*
 * Lazy mode
 */
public class Singleton2 {
	//1. The construction method is privatized, and objects are not allowed to be created directly from the outside
	private Singleton2(){
	}
}

 
Then three steps:
1. Change the constructor to private
2. Declare the only instance of the class, decorate it with private static, but not instantiate it
3. The class obtained by instantiating the unique object in the get method
is:

/*
 * Lazy mode
 */
public class Singleton2 {
	//1. The construction method is privatized, and objects are not allowed to be created directly from the outside
	private Singleton2(){
	}
	
	//2. Declare the only instance of the class, use private static modification
	private static Singleton2 instance;
	
	//3. Provide a method for obtaining an instance, decorated with public static
	public static Singleton2 getInstance(){
		if(instance==null){
			instance=new Singleton2();
		}
		return instance;
	}
}

 
Verify in Test.java class:

public class Test {
	public static void main(String[] args) {
		// hungry mode
		Singleton s1=Singleton.getInstance();
		Singleton s2=Singleton.getInstance();
		if(s1==s2){
			System.out.println("s1 and s2 are the same instance");
		}else{
			System.out.println("s1 and s2 are not the same instance");
		}
		
		// lazy mode
		Singleton2 s3=Singleton2.getInstance();
		Singleton2 s4=Singleton2.getInstance();
		if(s3==s4){
			System.out.println("s3 and s4 are the same instance");
		}else{
			System.out.println("S3 and s4 are not the same instance");
		}
	}
}

 
The result is obtained:
s1 and s2 are the same instance
, s3 and s4 are the same instance

, the difference between Hungry mode and lazy mode:
Hunger mode is characterized by slower loading of classes, but faster object acquisition at runtime and thread safety
The object instantiation in the lazy mode is when the class is loaded, so the loading speed is slower, but it is faster when the object is obtained.

Reference: http://www.imooc.com/learn/112

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326330629&siteId=291194637