一、含义:保证一个类只有一个实例,并提供一个访问它的全局访问点。
二、实现思路
(1)私有化构造方法
(2)类内部构建实例
(3)提供一个共有的静态方法,返回对象实例
三、七种实现代码
(1)饿汉式(静态常量)
public class SingletonHungry{
private SingletonHungry() {
}
private final static SingletonHungry instance=new SingletonHungry() ;
public static SingletonHungry getInstance() {
return instance;
}
}
(2)饿汉式(静态代码块)
public class SingletonHungry {
private SingletonHungry() {
}
private final static SingletonHungry instance ;
static {
instance = new SingletonHungry();
}
public static SingletonHungry getInstance() {
return instance;
}
}
(3)懒汉式(线程不安全)
public class SingletonLazy {
private SingletonLazy() {}
private static SingletonLazy instance;
public static SingletonLazy getInstance() {
if (instance == null) {
instance =new SingletonLazy();
}
return instance;
}
}
(4)懒汉模式(synchronized)
public class SingletonLazy {
private SingletonLazy() {}
private static SingletonLazy instance;
public static synchronized SingletonLazy getInstance() {
if (instance ==null) {
instance = new SingletonLazy();
}
return instance;
}
}
(5)懒汉式(双重检查)
public class SingletonLazy {
private SingletonLazy() {}
private static volatile SingletonLazy instance;
public static SingletonLazy getInstance() {
if (instance ==null) {
synchronized (SingletonLazy.class) {
if (instance==null) {
instance=new SingletonLazy();
}
}
}
return instance;
}
}
(6)懒汉模式 静态内部类
public class SingletonStaticClass {
private SingletonStaticClass() {
}
private static class SingletonStaticClassInstance{
private static final SingletonStaticClass instance = new SingletonStaticClass();
}
public static SingletonStaticClass getInstance() {
return SingletonStaticClassInstance.instance;
}
}
(7)枚举
enum SingletonEnum {
INSTANCE;
public SingletonEnum getInstance(){
return INSTANCE;
}
}