Thread-safe singleton pattern implementation class

 

Singleton (Singleton Pattern) is one of the easiest in Java design patterns. This type of design pattern belongs create schema, which provides the best way to create objects.

 

This model involves a single class that is responsible for creating your own objects, while ensuring that only a single object is created.

This class provides the only way to access the object can directly access, no instance of the object class.
Only one singleton class instance.
Singleton class must create their own unique instance.
Singleton class must provide this example to all other objects.

1. Singleton - thread-safe starving mode

public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){

}
public static Singleton getInstance(){
return instance;
}
}

2. singleton - thread-safe lazy mode 

public class Singleton {
private static Singleton instance = null;
private Singleton(){

}
  //如果不加synchronized,则是线程不安全的
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}

3. Singleton - thread-safe lazy mode improved version (double checking locks)

/ ** 
* double lock: in order to reduce the synchronization overhead
* /
public class the Singleton {
// static visible examples
Private volatile static instance the Singleton = null;
// no argument constructor
Private the Singleton () {

}
public the Singleton the getInstance () {
IF (instance == null) {
the synchronized (Singleton.class) {
IF (instance == null) {
instance the Singleton new new = ();
}
}
}
return instance;
}
}

4. Singleton - private internal factory class (thread-safe)

public class Singleton {
private Singleton(){
}

public static Singleton getInstance(){
return SingletonFactory.Instance;
}

private static class SingletonFactory{
private static Singleton Instance = new Singleton();
}
}
//内部类也可以换成内部接口,但是工厂类变量的作用域需为public

Guess you like

Origin www.cnblogs.com/cdlyy/p/12046618.html