对于系统中的某些类来说,只有一个实例很重要,例如,一个系统只能有一个窗口管理器或文件系统;一个系统只能有一个计时工具或ID(序号)生成器。
package com.jasongj.singleton1;
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
package com.jasongj.singleton2;
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {};
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
package com.jasongj.singleton3;
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}
synchronized
,但本质上是线程不安全的。 package com.jasongj.singleton4;
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized(Singleton.class){
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
package com.jasongj.singleton5;
public class Singleton {
private static volatile Singleton INSTANCE;
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
volatile
修饰 INSTANCE
,避免由于多线性同步和可见性问题造成的多实例 package com.jasongj.singleton6;
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {};
public static Singleton getInstance() {
return INSTANCE;
}
}
package com.jasongj.singleton7;
public class Singleton {
private static Singleton INSTANCE;
static{
INSTANCE = new Singleton();
}
private Singleton() {};
public static Singleton getInstance() {
return INSTANCE;
}
}
package com.jasongj.singleton8;
public class Singleton {
private Singleton() {};
public static Singleton getInstance() {
return InnerClass.INSTANCE;
}
private static class InnerClass {
private static final Singleton INSTANCE = new Singleton();
}
}
getInstance
时才会装载内部类,才会创建实例 package com.jasongj.singleton9;
public enum Singleton {
INSTANCE;
public void whatSoEverMethod() { }
}