Java learning singleton

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43271086/article/details/91406655

Singleton class: If only a class creates an instance, it is called singleton.

Use: When creating too many instances of this class does not make much sense when you can use, like most of the time the constructor is defined as public access, where we should be modified constructor private so the class constructor hide. But the process had to create objects of this class, you have to provide a public access point of the class as a method for creating and modifying the method must be static (because there is no class before calling the object produced, the use of the impossible method is an object, only the class)

Outside the first, the class must also cached object has been created, otherwise it is impossible to determine whether the object has been created, there is no guarantee create only one object. We use a member variable to hold the object has been created, because the member variables need to be above the static method to access, so must be modified with static

Code Display

import javax.xml.crypto.dsig.SignedInfo;

public class Singleton {
    private static Singleton instance;
    private Singleton(){};
    //静态方法才能访问静态变量
    public static Singleton getInstance(){
        if(instance==null){
            instance=new Singleton();
        }
        return  instance;
    }

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

Explanation: The final output is true, because there is only one object generator, s1 and s2 so that reference the same memory area, so the output is true

Guess you like

Origin blog.csdn.net/weixin_43271086/article/details/91406655