方法一
/**
* 懶漢模式,線程不安全
*/
public class Singleton1 {
private static Singleton1 instance;
private Singleton1(){}
public static Singleton1 getInstance(){
if (instance == null){
instance = new Singleton1();
}
return instance;
}
}
方法二
/**
* 懶漢模式,線程安全
*/
public class Singleton2 {
private static Singleton2 instance;
private Singleton2(){}
public static synchronized Singleton2 getInstance(){
if (instance == null){
instance = new Singleton2();
}
return instance;
}
}
方法三
/**
* 惡漢模式(標版)
*/
public class Singleton3 {
private static Singleton3 instance = new Singleton3();
private Singleton3(){}
public static Singleton3 getInstance(){
return instance;
}
}
方法四
/**
* 惡漢(變形)
*/
public class Singleton4 {
private static Singleton4 instance = null;
static {
instance = new Singleton4();
}
private Singleton4(){}
public static Singleton4 getInstance(){
return instance;
}
}
方法五
/**
* 靜態內部類
*/
public class Singleton5 {
private static class SingletonHoler {
private static final Singleton5 INSTANCE = new Singleton5();
}
private Singleton5(){}
public static final Singleton5 getInstance(){
return SingletonHoler.INSTANCE;
}
}
方法六
/**
* 枚舉
*/
public enum Singleton6 {
INSTANCE;
public void whateverMethod(){
}
}
方法七
/**
* 雙重校驗鎖
*/
public class Singleton7 {
private volatile static Singleton7 instance;
private Singleton7(){}
public static Singleton7 getInstance(){
if (instance == null){
synchronized (Singleton7.class){
if (instance == null){
instance = new Singleton7();
}
}
}
return instance;
}
}