1、枚举法
enum Singleton {
INSTANCE;
public void doSomeThing() {}
}
2、静态内部类
public class Singleton {
private static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE:
}
}
3、双检锁
public class Singleton {
//volatile必须要加,禁止new操作的指令重排序
private static volatile Singleton INSTANCE = null;
private static final Object LOCK = new Object();
private Singleton() {}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized(LOCK) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
4、懒汉式
class Singleton{
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
private Singleton(){}
}
5、饿汉式(线程不安全,并发问题)
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
6、spring实现的单例
@Component
@Scope("singleton") //默认就是单例,可以不加
public class Singleton {
}
或
@Configuration
public class Configuration {
@Bean
@Scope("singleton") //默认就是单例,可以不加
public Singleton getSingleton() {
return new Singleton();
}
}