package com.concurrent.singleton;
/**
* 懒汉模式--双重同步锁机制
* 第一次调用时生成单例
* @author
*
*/
public class SingletonExample3 {
private SingletonExample3() {
}
private volatile static SingletonExample3 instance = null;
public static SingletonExample3 getInstance() {
if (instance==null) {
synchronized (SingletonExample3.class) {
if (instance==null) {
instance = new SingletonExample3();
}
}
}
return instance;
}
}
package com.concurrent.singleton;
/**
* 饿汉模式
* 类加载时生成单例
* @author
*
*/
public class SingletonExample1 {
private SingletonExample1() {
}
private static SingletonExample1 singletonExample1 = new SingletonExample1();
public static SingletonExample1 getInstance() {
return singletonExample1;
}
}
package com.concurrent.singleton;
/**
* 饿汉模式
* 类加载时生成单例
* @author
*
*/
public class SingletonExample2 {
private SingletonExample2() {
}
private static SingletonExample2 singleton = null;
static {
singleton = new SingletonExample2();
}
public static SingletonExample2 getInstance() {
return singleton;
}
}
package com.concurrent.singleton;
/**
* 枚举模式
* @author
*
*/
public class SingletonExample4 {
private SingletonExample4() {
}
public static SingletonExample4 getInstance() {
return Singleton.INSTANCE.getInstance();
}
private enum Singleton{
INSTANCE;
private SingletonExample4 singleton;
Singleton() {
singleton = new SingletonExample4();
}
private SingletonExample4 getInstance() {
return singleton;
}
}
}
package com.concurrent.singleton;
public class Singleton {
private Singleton() {
}
private static class SingletonBuilder {
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance() {
return SingleTonBuilder.singleton;
}
}