Most of the time, the class's constructor is defined as public access, allowing any class to freely create objects of that class, but at other times it can degrade the performance of the system, such as the cost of reclaiming objects, and in order to avoid the freedom of other classes to create the class, we can set the constructor of the class to a private property. Once the constructor of the class is defined as a private property, a public method must be provided, and a static adornment, because the object is not present when the method is called, so it is not an object to call the method, only a class, in addition to the object that has already been created must be cached. Otherwise, the class cannot know whether an object was created before, and there is no guarantee that an object is created, for which the class needs to use a member object to hold the object that was created, because the member variable needs to be accessed by the variable above.
Package Myproject;
public class Singleton {
private static Singleton Instanse;
Private Singleton () {}
public static singleton getinstance () {
if (instanse==null) {
Instanse=new Singleton ();
}
return instanse;
}
}
Package Myproject;
public class Mysingleton {
public static void Main (string[] args) {
Singleton s1=singleton.getinstance ();
Singleton s2=singleton.getinstance ();
}
}
Singleton S3=new Singleton ();//Such declaration method is wrong, cannot find the way of declaring.
Java Review-singleton Class