The singleton pattern is used to ensure that a class has and has only one instance during the running of a program. The advantage is to resolve system resources as much as possible. You can implement a single case pattern by modifying the access rights of the construction method.
The code is as follows:
Copy Code code as follows:
public class Emperor {
private static Emperor Emperor = null;//declares a reference to a Emperor class
Private Emperor () {//The construction method is proprietary
}
public static Emperor GetInstance () {//instantiated reference
if (emperor = = null) {
emperor = new Emperor ();
}
return emperor;
}
public void GetName () {//Use normal method to output the name of the emperor
System.out.println ("I Am the Emperor: Tomorrow Science and Technology");
}
}
public class Test {
public static void Main (string[] args) {
System.out.println ("Creation Emperor 1 Objects:");
Emperor Emperor1 = Emperor.getinstance ();//Create Emperor Object
Emperor1.getname ()//output Emperor's name
System.out.println ("Creation Emperor 2 objects:");
Emperor Emperor2 = Emperor.getinstance ();//Create Emperor Object
Emperor2.getname ()//output Emperor's name
System.out.println ("Creation Emperor 3 objects:");
Emperor Emperor3 = Emperor.getinstance ();//Create Emperor Object
Emperor3.getname ()//output Emperor's name
}
}
Effect as shown: