/**
* 单例设计模式
* 特点:全局只有一个对象;对应由单例类提供,单例类构造方法私有;单例类对外提供一个静态方法访问对象。
* 选择场景:
* 单线程使用 使用SingletonPattern
* 多线程使用 饿汉模式 SafeThredSingleton
* 多线程性能要求 MutiThreadSingleton 或者 InnerSingleton
*/
public class SingletonPattern {
private static SingletonPattern singletonPattern = null;
private SingletonPattern() {
}
/**
* 懒汉式获取单列对象
* 会有线程安全问题
*/
public static synchronized SingletonPattern getSingleton() {
if (singletonPattern == null) {
return new SingletonPattern();
}
return singletonPattern;
}
/**
* 线程安全 饿汉模式
*/
static class SafeThredSingleton {
private static SafeThredSingleton safeThredSingleton = new SafeThredSingleton();
private SafeThredSingleton() {
}
public static SafeThredSingleton getSafeThredSingleton() {
return safeThredSingleton;
}
}
/**
* 多线程性能最优,会存在指令重拍还是有问题的
*/
static class MutiThreadSingleton {
private static volatile MutiThreadSingleton mutiThreadSingleton = null;
private MutiThreadSingleton() {
}
public static MutiThreadSingleton getInstance() {
if (mutiThreadSingleton == null) {
synchronized (MutiThreadSingleton.class) {
if (mutiThreadSingleton == null) {
mutiThreadSingleton = new MutiThreadSingleton();
}
}
}
return mutiThreadSingleton;
}
}
/**
* 基于静态内部类
*/
static class InnerSingleton {
private InnerSingleton() {
}
;
private static class InnerClass {
private static final InnerSingleton innerSingleton = new InnerSingleton();
}
public static InnerSingleton getInstance() {
return InnerClass.innerSingleton;
}
}
}