Singleton mode ensures that only one instance of a class exists.
In a computer system, the driver objects of the thread pool, cache, log Object, dialog box, printer, and video card are often designed as singleton.
A hungry man method
publicclassSingleton {
private
static
Singleton =
new
Singleton();
private
Singleton() {}
public
static
getSignleton(){
return
singleton;
}
}A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe. However, you cannot defer creating objects.
Lazy Type
public
class
Singleton {
private
static
Singleton singleton =
null
;
private
Singleton(){}
public
static
Singleton getSingleton() {
if
(singleton ==
null
) singleton =
new
Singleton();
return
singleton;
}
}Lazy Singleton class. Instantiate yourself at the first call, without regard to thread safety, which is thread insecure
public
class
Singleton {
private
Singleton(){}
public
static
Singleton getSingleton(){
return
Holder.singleton;
}
private
static
class
Holder {
private
static
Singleton singleton =
new
Singleton();
}
}
through static internal classes, delayed loading, and thread-safe (this avoids the creation of static instances when the Singleton class is loaded, and because static inner classes are only loaded once, this is also thread-safe:)
Enumeration Notation
Public enum enumsingleton{
INSTANCE;
}
Access via Enumsingleton test=enumsingleton.instance
The use of enumerations, in addition to thread-safe and anti-reflection forced invocation of the constructor, also provides an automatic serialization mechanism to prevent deserialization when a new object is created. Therefore, effective Java recommends using enumerations as much as possible to implement the singleton.
Java Singleton mode