使用场景:需要频繁的进行创建和销毁的对象,创建对象耗时较多或耗费资源过多(重量级对象),经常用到的对象,工具类对象,访问数据库或者文件对象(比如数据源,session工厂等)。
推荐使用以下四种方式:
1.饿汉式
如果可以确定肯定会使用的话,也可以使用,懒汉式容易出问题不太推荐。
class Singleton{
private Singleton(){
}
private final static Singleton INSTANCE=new Singleton();
public static Singleton getInstance(){
return INSTANCE;
}
}
class Singleton{
private Singleton(){}
static {
INSTANCE=new Singleton();
}
private static Singleton INSTANCE;
public static Singleton getInstance(){
return INSTANCE;
}
}
2.dcl
class Singleton {
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
// 保证一个线程执行
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
3.静态内部类
//静态内部类推荐使用,运用jvm底层类装载的机制,保证线程安全
class Singleton {
private Singleton() {
}
private static class SingletonInstance {
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.instance;
}
}
4.枚举
public class SingletonTest {
public static void main(String[] args) {
Singleton instance = Singleton.instance;
Singleton instance1 = Singleton.instance;
System.out.println(instance == instance1);
System.out.println(instance.hashCode());
System.out.println(instance1.hashCode());
}
}
//枚举实现单例推荐使用
enum Singleton {
instance;
}