-
单例模式:所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。
-
比如Hibernate的SessionFactory,它充当数据存储源的代理,并负责创建Session对象。SessionFactory并不是轻量级的,一般情况下,一个项目通常只需要一个SessionFactory就够,这是就会使用到单例模式。
-
单例模式有八种方式:
- 饿汉式(静态常量)
// 静态常量式饿汉模式 class Singleton{ // 1、构造器私有化,外部能new private Singleton(){} // 2、本类内部构建对象实例 private final static Singleton instance = new Singleton(); // 3、提供一个公共的静态方法,返回实例对象。 public static Singleton getInstance() { return instance; } } public class SingletonTest { public static void main(String[] args) { Singleton instance = Singleton.getInstance(); Singleton instance1 = Singleton.getInstance(); System.out.println(instance == instance1); // 结果:true } }
- 饿汉式(静态代码块)
public class SingletonStaticCode{ // 1、构造器私有化,外部能new private SingletonStaticCode(){ } // 2、本类内部构建对象实例 private final static SingletonStaticCode instance; // 在静态代码块中,创建单例对象 static{ instance = new SingletonStaticCode(); } // 3、提供一个公共的静态方法,返回实例对象。 public static SingletonStaticCode getInstance() { return instance; } }
- 懒汉式(线程不安全)
public class SingletonLazy01 { private static SingletonLazy01 instance; public SingletonLazy01() { } //提供一个静态的公有方法,当使用到该方法时,才去创建instance // 即懒汉式 public static SingletonLazy01 getInstance() { if (instance == null){ instance =new SingletonLazy01(); } return instance; } }
- 懒汉式(线程安全,同步方法)
public class SingletonLazy01 { private static SingletonLazy01 instance; public SingletonLazy01() { } //提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题 public static synchronized SingletonLazy01 getInstance() { if (instance == null){ instance =new SingletonLazy01(); } return instance; } }
- 双重检查
public class SingletonLazy { private static volatile SingletonLazy instance; public SingletonLazy() {} //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题 public static SingletonLazy getInstance() { if (instance == null){ synchronized(SingletonLazy.class){ if (instance == null){ instance =new SingletonLazy(); } } } return instance; } }
- 静态内部类
public class SingletonLazy { private SingletonLazy() {} private static class Singleton{ private static final SingletonLazy instance = new SingletonLazy(); } public static SingletonLazy getInstance(){ return Singleton.instance; } }
- 枚举实现单例
enum Singleton { INSTANCE; public void sayOK(){ System.out.println("ok~"); } }