Singleton design pattern (Java)

Singleton design pattern

The so-called singleton design pattern of a class is to adopt a certain method to ensure that there can only be one object instance for a certain class in the entire software system.

Hungry Chinese

Method 1: Use static methods and static objects

class Bank{
    
    
	
	//1.私化类的构造器
	private Bank(){
    
    
		
	}
	
	//2.内部创建类的对象
	//4.要求此对象也必须声明为静态的
	private static Bank instance = new Bank();
	
	//3.提供公共的静态的方法,返回类的对象
	public static Bank getInstance(){
    
    
		return instance;
	}
}

Method 2: Use static code blocks

class Order{
    
    
	
	//1.私化类的构造器
	private Order(){
    
    
		
	}
	
	//2.声明当前类对象,没初始化
	//4.此对象也必须声明为static的
	private static Order instance = null;

	static{
    
    
		instance = new Order();
 }
	
	//3.声明public、static的返回当前类对象的方法
	public static Order getInstance(){
    
    
		return instance;
	}
	
}

Lazy man

class Bank{
    
    

	//1.私化类的构造器
    private Bank(){
    
    }
    
	//2.声明当前类对象,没初始化
	//4.此对象也必须声明为static的
    private static Bank instance = null;

	//3.声明public、static的返回当前类对象的方法
    public static Bank getInstance(){
    
    

        if(instance == null){
    
    
			
			//使用synchronized锁确保线程安全
            synchronized (Bank.class) {
    
    
                if(instance == null){
    
    

                    instance = new Bank();
                }

            }
        }
        return instance;
    }

}

Hungry Chinese Style:
Benefits: It is thread-safe in nature, no locks are required, and easy to modify and maintain.
Disadvantages: the object loading time is too long.

Lazy style:
Benefits: Delay the creation of objects.
Disadvantage: Need to use synchronization mechanism (lock) to ensure thread safety.

Guess you like

Origin blog.csdn.net/m0_50654102/article/details/114289138