A hungry man single-case mode:
Package Com.design.singleton; Public class Eagersingleton { privatestaticfinalnew Eagersingleton (); Private Eagersingleton () {} publicstatic Eagersingleton getinstance () { return Eager_singleton; }}
When this class is loaded, the static variable Eager_singleton is initialized.
Lazy Single-Case:
PackageCom.design.singleton; Public classLazysingleton {Private StaticLazysingleton Lazysingleton =NULL; PrivateLazysingleton () {} Public synchronized StaticLazysingleton getinstance () {if(Lazysingleton = =NULL){ return NewLazysingleton (); } returnLazysingleton; }}
the "difference" a hungry man singleton mode instantiates itself when it is loaded. From the perspective of resource utilization, a hungry man is almost the same as the lazy. In terms of speed and reaction time, a hungry man is more than a lazy block. Lazy in the instantiation of the time, need to deal with multi-threaded problems.
There's a lot more to use.
Static internal class Single example:
PackageCom.design.singleton; Public classInnersingleton {PrivateInnersingleton () {}Private Static classinner{Private StaticInnersingleton Instance =NewInnersingleton (); } Public StaticInnersingleton getinstance () {returninner.instance; } Public voiddosomething () {//Do something } }
This single thread-safe
Java design Pattern--Singleton mode