The most basic implementation methods are as follows:
Copy Code code as follows:
Package Singletonpattern;
public class Singleton1 {
private static Singleton1 uniqueinstance;
Private Singleton1 () {
}
public static Singleton1 getinstance () {
if (uniqueinstance = = null) {
Uniqueinstance = new Singleton1 ();
}
return uniqueinstance;
}
}
However, the above methods do not take into account the situation of multithreading, if it is multiple threads, it is possible to create multiple instances, so you can add locks and synchronization to achieve multithreaded single mode, synchronization is the disadvantage of the efficiency is greatly reduced:
Copy Code code as follows:
Package Singletonpattern;
public class Singleton2 {
private static Singleton2 uniqueinstance;
Private Singleton2 () {
}
public static synchronized Singleton2 getinstance () {
if (uniqueinstance = = null) {
Uniqueinstance = new Singleton2 ();
}
return uniqueinstance;
}
}
Another method is to initialize automatically, which will certainly not cause multiple instances, but will initialize the instance if it is not actually used, wasting resources:
Copy Code code as follows:
Package Singletonpattern;
public class Singleton3 {
private static Singleton3 uniqueinstance = new Singleton3 ();
Private Singleton3 () {
}
public static Singleton3 getinstance () {
return uniqueinstance;
}
}
Methods that use internal classes can solve premature initialization problems:
Copy Code code as follows:
public class Singleton5 {
Private Singleton5 () {
}
public static Singleton5 getinstance () {
return nested.instance;
}
Static Class nested{
Static SINGLETON5 instance = new Singleton5 ();
}
}
Ways to improve multithreading are as follows:
Copy Code code as follows:
Package Singletonpattern;
public class Singleton4 {
Private volatile static Singleton4 uniqueinstance;
Private Singleton4 () {
}
public static Singleton4 getinstance () {
if (uniqueinstance = = null) {
Synchronized (Singleton4.class) {
if (uniqueinstance = = null) {
Uniqueinstance = new Singleton4 ();
}
}
}
return uniqueinstance;
}
}
Double-check is used, and the lock and sync are performed when no instantiation occurs.