1.1 单例模式介绍

所谓类的单例设计模式,就是采取肯定的办法保障在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个获得其对象实例的办法(静态方法)。

比方 Hibernate 的 SessionFactory,它充当数据存储源的代理,并负责创立 Session 对象。SessionFactory 并不是轻量级的,个别状况下,一个我的项目通常只须要一个 SessionFactory 就够,这是就会应用到单例模式。

单例模式八种形式

  • 饿汉式 ( 动态常量 )
  • 饿汉式(动态代码块)
  • 懒汉式(线程不平安)
  • 懒汉式(线程平安,同步办法)
  • 懒汉式(线程平安,同步代码块)
  • 双重查看
  • 动态外部类
  • 枚举

1.2 饿汉式(动态常量)

利用实例

步骤如下:

  1. 结构器私有化 (避免 new)
  2. 类的外部创建对象
  3. 向外裸露一个动态的公共办法 getInstance
  4. 代码实现

    public class SingletonDemo01 {    public static void main(String[] args) {        Singleton01 instance01 = Singleton01.getInstance();        Singleton01 instance02 = Singleton01.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 饿汉式--动态常量 */class Singleton01 {    // 1.构造方法私有化,内部不能 new    private Singleton01() {    }    // 2.定义动态变量    public final static Singleton01 instance = new Singleton01();    // 3.向外裸露一个静态方法    public static Singleton01 getInstance() {        return instance;    }}

优缺点阐明

  1. 长处:这种写法比较简单,就是在类装载的时候就实现实例化,防止了线程同步问题。
  2. 毛病:在类装载的时候就实现实例化,没有达到 LazyLoading 的成果。如果从始至终从未应用过这个实例,则会造成内存的节约。
  3. 这种形式基于 classloder 机制防止了多线程的同步问题,不过,instance 在类装载时就实例化,在单例模式中大多数都是调用 getInstance 办法,然而导致类装载的起因有很多种,因而不能确定有其余的形式(或者其余的静态方法)导致类装载,这时候初始化 instance 就没有达到 lazyloading 的成果。
  4. 论断:这种单例模式可用,可能造成内存节约

1.3 饿汉式(动态代码块)

利用实例

public class SingletonDemo02 {    public static void main(String[] args) {        Singleton02 instance01 = Singleton02.getInstance();        Singleton02 instance02 = Singleton02.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 饿汉式--动态代码块 */class Singleton02 {    // 1.构造方法私有化,内部不能 new    private Singleton02() {    }    // 2.定义动态变量    public static Singleton02 instance;    // 3.动态代码块    static {        instance = new Singleton02();    }    // 4.向外裸露一个静态方法    public static Singleton02 getInstance() {        return instance;    }}

优缺点阐明

  1. 这种形式和下面的形式其实相似,只不过将类实例化的过程放在了动态代码块中,也是在类装载的时候,就执行动态代码块中的代码,初始化类的实例。优缺点和下面是一样的。
  2. 论断:这种单例模式可用,然而可能造成内存节约

1.4 懒汉式(线程不平安)

利用实例

public class SingletonDemo03 {    public static void main(String[] args) {        Singleton03 instance01 = Singleton03.getInstance();        Singleton03 instance02 = Singleton03.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 懒汉式--线程不平安 */class Singleton03 {    // 1.构造方法私有化,内部不能 new    private Singleton03() {    }    // 2.创立动态常量    private static Singleton03 instance;    // 3.创立静态方法,供内部调用,当须要实例时,才去创立 instance    public static Singleton03 getInstance() {        if (instance == null) {            instance = new Singleton03();        }        return instance;    }}

优缺点阐明

  1. 起到了 LazyLoading 的成果,然而只能在单线程下应用。
  2. 如果在多线程下,一个线程进入了 if(singleton==null) 判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例,造成线程不平安,所以在多线程环境下不可应用这种形式。
  3. 论断:在理论开发中,不要应用这种形式.

1.5 懒汉式(线程平安,同步办法)

利用实例

public class SingletonDemo04 {    public static void main(String[] args) {        Singleton04 instance01 = Singleton04.getInstance();        Singleton04 instance02 = Singleton04.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 懒汉式--线程平安 */class Singleton04{    // 1.构造方法私有化,内部不能 new    private Singleton04() {    }    // 2.创立动态常量    private static Singleton04 instance;    // 3.创立静态方法,供内部调用,当须要实例时,才去创立 instance    // 4.退出 synchronized 关键字,解决线程不齐全问题    public static synchronized Singleton04 getInstance() {        if (instance == null) {            instance = new Singleton04();        }        return instance;    }}

优缺点阐明

  1. 解决了线程平安问题。
  2. 效率太低了,每个线程在想取得类的实例时候,执行 getInstance() 办法都要进行同步。而其实这个办法只执行一次实例化代码就够了,前面的想取得该类实例,间接return就行了。办法进行同步效率太低。
  3. 论断:在理论开发中,不举荐应用这种形式

1.6 懒汉式(线程平安,同步代码块)

利用实例

public class SingletonDemo05 {    public static void main(String[] args) {        Singleton05 instance01 = Singleton05.getInstance();        Singleton05 instance02 = Singleton05.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 懒汉式--线程平安--同步代码块 */class Singleton05{    // 1.构造方法私有化,内部不能 new    private Singleton05() {    }    // 2.创立动态常量    private static Singleton05 instance;    // 3.创立静态方法,供内部调用,当须要实例时,才去创立 instance    // 4.应用同步代码块    public static Singleton05 getInstance() {        if (instance == null) {            synchronized (Singleton05.class) {                instance = new Singleton05();            }        }        return instance;    }}

优缺点阐明

  1. 论断:在理论开发中,不能应用这种形式

1.7 双重查看

利用实例

public class SingletonDemo06 {    public static void main(String[] args) {        Singleton06 instance01 = Singleton06.getInstance();        Singleton06 instance02 = Singleton06.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 双重查看 */class Singleton06 {    // 1.构造方法私有化,内部不能间接 new    private Singleton06 () {    }    // 2.创立动态常量    private static Singleton06 instance;    // 3.提供静态方法,供内部调用    // 4.应用双重查看,即实现了懒加载的成果,又保障了线程平安,举荐应用    public static Singleton06 getInstance() {        if (instance == null) {            synchronized (Singleton06.class) {                if (instance == null) {                    instance = new Singleton06();                }                return instance;            }        }        return instance;    }}

优缺点阐明

  1. Double-Check 概念是多线程开发中常应用到的,如代码中所示,咱们进行了两次 if(singleton==null) 查看,这样就能够保障线程平安了。
  2. 这样,实例化代码只用执行一次,前面再次拜访时,判断 if(singleton==null) ,间接 return 实例化对象,也防止的重复进行办法同步。
  3. 线程平安、提早加载、效率较高。
  4. 论断:在理论开发中,举荐应用这种单例设计模式

1.8 动态外部类

利用实例

public class SingletonDemo07 {    public static void main(String[] args) {        Singleton07 instance01 = Singleton07.getInstance();        Singleton07 instance02 = Singleton07.getInstance();        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 应用动态外部类的形式实现单例模式 */class Singleton07 {    // 1.构造方法私有化,内部不能间接 new    private Singleton07() {    }    // 2.创立一个动态外部类    private static class Singleton07Instance {        private static final Singleton07 INSTANCE = new Singleton07();    }    // 3.创立一个静态方法,供内部调用    // 4.JVM 在加载类的时候不会加载动态外部类,在应用到动态外部类的时候才会加载,这样既保证了懒加载的成果,又保障了线程平安    public static Singleton07 getInstance() {        return Singleton07Instance.INSTANCE;    }}

优缺点阐明

  1. 这种形式采纳了类装载的机制来保障初始化实例时只有一个线程。
  2. 动态外部类形式在 Singleton 类被装载时并不会立刻实例化,而是在须要实例化时,调用 getInstance 办法,才会装载 SingletonInstance 类,从而实现 Singleton 的实例化。
  3. 类的动态属性只会在第一次加载类的时候初始化,所以在这里,JVM 帮忙咱们保障了线程的安全性,在类进行初始化时,别的线程是无奈进入的。
  4. 长处:防止了线程不平安,利用动态外部类特点实现提早加载,效率高
  5. 论断:举荐应用

1.9 枚举

利用实例

public class SingletonDemo08 {    public static void main(String[] args) {        Singleton08 instance01 = Singleton08.INSTANCE;        Singleton08 instance02 = Singleton08.INSTANCE;        System.out.println(instance01 == instance02); // true        System.out.println("instance01 hashcode=" + instance01.hashCode());        System.out.println("instance02 hashcode=" + instance02.hashCode());    }}/** * 应用枚举的形式实现单例模式 */enum Singleton08 {    INSTANCE;}

优缺点阐明

  1. 这借助 JDK 1.5 中增加的枚举来实现单例模式,不仅能防止多线程同步问题,而且还能避免反序列化从新创立新的对象。
  2. 这种形式是 EffectiveJava 作者 JoshBloch 提倡的形式。
  3. 论断:举荐应用

1.10 单例模式在JDK利用的源码剖析

  1. JDK 中,java.lang.Runtime 就是经典的单例模式(饿汉式)
  2. 代码剖析 + Debug 源码 + 代码阐明

    public class Runtime {    // 应用动态常量的形式实现单例模式    private static Runtime currentRuntime = new Runtime();    /**     * Returns the runtime object associated with the current Java application.     * Most of the methods of class <code>Runtime</code> are instance     * methods and must be invoked with respect to the current runtime object.     *     * @return  the <code>Runtime</code> object associated with the current     *          Java application.     */    public static Runtime getRuntime() {        return currentRuntime;    }    /** Don't let anyone else instantiate this class */    private Runtime() {}}

1.11 单例模式注意事项和细节阐明

  1. 单例模式保障了零碎内存中该类只存在一个对象,节俭了系统资源,对于一些须要频繁创立销毁的对象,应用单例模式能够进步零碎性能
  2. 当想实例化一个单例类的时候,必须要记住应用相应的获取对象的办法,而不是应用 new。
  3. 单例模式应用的场景:须要频繁的进行创立和销毁的对象、创建对象时耗时过多或消耗资源过多(即:重量级对象),但又常常用到的对象、工具类对象、频繁拜访数据库或文件的对象(比方数据源、 session 工厂等)。