The A Hungry Man method implementation code is as follows:
PackagePriv.jack.dp.demo.singleton;/** * @authorJack * A hungry man mode singleton * Thread safety * does not support lazy loading, easy to generate garbage objects * Advantages: No lock, execution efficiency will improve. */ Public classHungrysingleton {Private StaticHungrysingleton INSTANCE =NewHungrysingleton (); PrivateHungrysingleton () {System.out.println ("Init ..."); } Public voidHello () {System.out.println ("Hello world!"); } Public StaticHungrysingleton getinstance () {returnINSTANCE; } Public Static voidmain (String [] args) {System.out.println ("Main start ..."); Hungrysingleton.getinstance (). hello (); }}
Static inner class implementation code:
PackagePriv.jack.dp.demo.singleton;/** * @authorJack * Supports lazy loading, multi-threaded * objects are created at the time of use*/ Public classStaticinnersingleton {Private Static classstaticinnersingletonholder{Private Static FinalStaticinnersingleton INSTANCE =NewStaticinnersingleton (); } PrivateStaticinnersingleton () {System.out.println ("Init ..."); } Public Static FinalStaticinnersingleton Getinstantce () {returnstaticinnersingletonholder.instance; } Public voidHello () {System.out.println ("Hello world!"); } Public Static voidmain (String [] args) {System.out.println ("Main start ..."); Staticinnersingleton.getinstantce (). hello (); } }
A hungry man mode run result
init...main Start...hello World!
Static internal class mode run result
main Start...init...hello world!
The difference is that static internal classes are lazy-loaded and take into account high-performance benefits.
The difference between the implementation of the A Hungry man mode and the static inner class implementation of the Singleton pattern