Package Com.imooc;/** Single case Mode singleton * Application: Some objects need only one is enough. * Function: Ensure that an instance of the entire application has only one * type: A hungry man mode, lazy mode * **/Public class Singleton {//1. Privatize the construction method and do not allow external direct creation of objectsPrivate Singleton () {}//2. Create a unique instance of the class, using the private static adornmentprivate static Singleton instance=NewSingleton (); //3. Provide a method for obtaining an instance, using the public static modifierPublic static Singleton getinstance () {returninstance; }}
Usage patterns
Package Com.imooc;public class Test { void main (string[] args) { Singleton s1= Singleton.getinstance (); Singleton s2=singleton.getinstance (); if (s1==S2) { System.out.println ("S1 and sI2 are the same instance"); } Else { System.out.println ("S1 and time is not the same instance") ; }}}
A hungry man mode of single case mode