Java: Singleton pattern

Singleton mode means that when we get an object, we can only get the same object. To achieve Singleton pattern, we must meet several conditions must first have privatized static object references , constructor privatization , privatization is to prevent arbitrary external class called to create the object. Then provide an external method to obtain the object .

We describe two factory pattern, lazy man's load and hungry Chinese-style load .

1. Lazy loading

Create the object when you get the object for the first time

public class Singleton_01 {
    
    
	
	//声明静态变量
	private static Singleton_01 s;
	
	//构造方法私有化,外部不能创建对象
	private Singleton_01(){
    
    
		
	}
	
	//在获取对象时,先判断对象是否被实例化
	//如果对象还没有被创建,就创建
	//如果已经被实例化,则直接返回对象
	public static Singleton_01 getInstance(){
    
    
		if(s == null){
    
    
			s = new Singleton_01();
		}
		
		return s;
	}
	
}

2. Hungry Chinese loading

The object is created when the class is loaded

public class Singleton_02 {
    
    
	
	//在类加载的时候就直接创建对象
	private static Singleton_02 s = new Singleton_02();

	//构造方法私有化,外部不能创建对象
	private Singleton_02(){
    
    
		
	}
	
	//对外提供的获取对象的方法,公共的
	public static Singleton_02 getInstance(){
    
    
		return s;
	}
}

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/112850930