懒汉模式
@ThreadSafe
public class SingletonExample1 {
//私有的构造函数
private SingletonExample1() {
}
//单列对象
private static SingletonExample1 instance = null;
//静态的工厂方法
public static synchronized SingletonExample1 getInstance() {
if (instance == null) {
instance = new SingletonExample1();
}
return instance;
}
}
饿汉模式
@ThreadSafe
public class SingletonExample2 {
//私有的构造函数
private SingletonExample2() {
}
//单列对象
private static SingletonExample2 instance = new SingletonExample2();
//静态的工厂方法
public static SingletonExample2 getInstance() {
return instance;
}
}
双重同步锁单例模式
@ThreadSafe
public class SingletonExample4 {
//私有的构造函数
private SingletonExample4() {
}
//单列对象
private static SingletonExample4 instance = null;
//静态的工厂方法
public static SingletonExample4 getInstance() {
if (instance == null) {
synchronized (SingletonExample4.class){
if(instance==null){
instance = new SingletonExample4();
}
}
}
return instance;
}
}
volatile+双重同步锁单例模式
@ThreadSafe
public class SingletonExample5 {
//私有的构造函数
private SingletonExample5() {
}
//volatile+双重同步锁单例模式》 关键字可以防止cup指令重排
//单列对象
private volatile static SingletonExample5 instance = null;
//静态的工厂方法
public static SingletonExample5 getInstance() {
if (instance == null) {
synchronized (SingletonExample5.class){
if(instance==null){
instance = new SingletonExample5();
}
}
}
return instance;
}
}
静态的工厂方法
@ThreadSafe
public class SingletonExample6 {
//私有的构造函数
private SingletonExample6() {
}
//单列对象
private static SingletonExample6 instance =null;
static {
instance = new SingletonExample6();
}
//静态的工厂方法
public static SingletonExample6 getInstance() {
return instance;
}
public static void main(String[] args) {
System.out.println(getInstance().hashCode());
System.out.println(getInstance().hashCode());
}
}
枚举
@ThreadSafe
public class SingletonExample7 {
private SingletonExample7() {
}
public static SingletonExample7 getInstance() {
return Singleton.INSTANCE.getInstance();
}
private enum Singleton {
INSTANCE;
private SingletonExample7 singleton;
//JVM保证这个方法只被调用一次
Singleton() {
singleton = new SingletonExample7();
}
public SingletonExample7 getInstance() {
return singleton;
}
}
}
网友评论