A hungry man mode of the singleton mode:
Sample Code ↓
1 classdemo{2 Private StaticDemo obj =NewDemo ();//Save this type of static private field in this class3 PrivateDemo () {}//privatization constructors make this class outside of the instantiation4 Public StaticDemo getinstance () {//Life public static method obtains instances of this class by this method5 if(obj==NULL)//determines whether an object is empty6obj =NewDemo ();7 returnobj;8 }9}
The above-mentioned scenario is called the A hungry man pattern because this way of implementing a singleton pattern is immediately created when the program loads into the Java virtual machine.
Cons: Affects the speed at which the loader is loaded.
Advantage: Faster when getting objects.
The lazy mode of the singleton mode:
Sample Code ↓
1 classdemo{2 Private StaticDemo obj;//Save this type of static private field in this class3 PrivateDemo () {}//privatization constructors make this class outside of the instantiation4 Public StaticDemo getinstance () {//Statementexposes a static method to obtain an instance of this class through this method5 if(obj==NULL)//determines whether an object is empty6obj =NewDemo ();7 returnobj;8 }9}
The above situation is called lazy mode because this way the program is loaded into the Java Virtual machine only declares a field does not create an instance until the first time the instance is created
Cons: The first time you get an instance is slower.
Advantages: It will not affect the loading speed of the program, reduce the user's waiting time.
PS: Above for personal understanding, if there is any wrong place, welcome the comments below to specify.
design mode → Singleton mode