An example application of the Java singleton pattern

  • 2020-04-01 03:00:02
  • OfStack

The singleton pattern is used to ensure that there is only one instance of a class during the program's run. Its advantage is to solve the system resources as much as possible. The singleton pattern can be implemented by modifying the constructor's access rights.

The code is as follows:


public class Emperor {
    private static Emperor emperor = null;//Declares a reference to the Emperor class
    private Emperor() {//Private the constructor
    }
    public static Emperor getInstance() {//Instantiated reference
        if (emperor == null) {
            emperor = new Emperor();
        }
        return emperor;
    }
    public void getName() {//Output the name of the emperor using the common method
        System.out.println(" I am the emperor: tomorrow technology ");
    }
}
public class Test {
    public static void main(String[] args) {
        System.out.println(" Create the emperor 1 Object: ");
        Emperor emperor1 = Emperor.getInstance();//Create the emperor object
        emperor1.getName();//Print the name of the emperor
        System.out.println(" Create the emperor 2 Object: ");
        Emperor emperor2 = Emperor.getInstance();//Create the emperor object
        emperor2.getName();//Print the name of the emperor
        System.out.println(" Create the emperor 3 Object: ");
        Emperor emperor3 = Emperor.getInstance();//Create the emperor object
        emperor3.getName();//Print the name of the emperor
    }
}

The effect is as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201402/2014221153817533.png" >


Related articles: