验证中...
懒汉模式-线程不安全
Raw Copy
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉模式-线程安全
Raw Copy
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
饿汉模式
Raw Copy
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){
}
public static Singleton getInstance() {
return instance;
}
}
饿汉模式-变种
Raw Copy
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
静态内部类
Raw Copy
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){
}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
双重校验锁
Raw Copy
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
枚举
Raw Copy
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}

Comment list( 5 )

又是空白 2018-04-04 09:25

新手表示老是记不住啊,要知道什么原理才能更好理解为什么代码顺序要那么写呢

390077_xuliugen
徐刘根 2018-02-13 21:20

@javaalpha 静态内部类的那种方式,个人墙裂推荐

562689_javaalpha
javaalpha 2018-01-09 18:34

你觉得哪种模式最推荐呢?

390077_xuliugen
徐刘根 2017-10-19 20:42

@123 已改

1239477_qq1971237545com
123 2017-10-19 15:09

第四种写法有误啊!

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025