In the development of the time, we in some cases some objects we only need one. For example: Configuration files, tool classes, thread pools, caches, log objects, and so on.
How do we ensure that we have only one object? We can do this by single example .
There are two common types of singleton: a hungry man mode and lazy mode.
a hungry man mode : This singleton object is created when the class is loaded. (Load slower, but run faster, thread safe )
public class Singleton {//1. The construction method is set to private, the object of the class is not allowed to be instantiated directly by the outside world Private Singleton () {}//2. Create a private static instance object private static Singleton Instance = new Singleton ();//3. Obtaining an instance object through a common static method public static Singleton getinstance () {return instance;}}
Lazy Mode : Class loading does not create a singleton for the class, only the first time the getinstance () method is called, a singleton of the class is created. (Fast loading, runtime for first time slow, non-thread safe )
public class Singleton {//1. Sets the construction method to private and does not allow the outside world to instantiate objects directly from the class private Singleton () {}//2. Declares a unique instance of a class, using private static to modify private Static Singleton INSTANCE;//3. Get instance object public static Singleton getinstance () {if (instance = null) through a common static method {instance = New Singleton ();} return instance;}}
Single case Mode singleton