A single case pattern can be obtained by means of privatization and flexible application of static. After you have privatized the constructor, you can no longer create objects with new. A static method can only be called from a class name to get a singleton object (one of the objects).
Class Singleton{private static Singleton instance = new Singleton ();p rivate Singleton () {}public void print () {System.out. println ("Hello, singleton!");} public static Singleton getinstance () {return instance;}} public class SingleDemo01 {public static void main (string[] args) {//TODO auto-generated method Stubsingleton S1 = Single Ton.getinstance (); Singleton s2 = singleton.getinstance (); Singleton s3 = Singleton.getinstance (); S1.print (); S2.print (); S3.print ();}}
At this point, no matter how many objects, there is actually only one instance
Java Singleton mode