关于设计模式:史上最全讲解单例模式以及分析源码中的应用

6次阅读

共计 9280 个字符,预计需要花费 24 分钟才能阅读完成。

1、单例模式介绍

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

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

2、单例模式的品种

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

1、饿汉式(动态常量)

步骤:

  • 构造方法私有化
  • 内的外部创建对象
  • 向外裸露一个动态的公共办法
public class Singleton01 {private static final Singleton01 INSTANCE = new Singleton01();

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton01(){}

    /**
     * 提供一个私有的静态方法,返回实例对象
     * @return INSTANCE
     */
    public static Singleton01 getINSTANCE() {return INSTANCE;}

    public static void main(String[] args) {Singleton01 instance1 = Singleton01.getINSTANCE();
        Singleton01 instance2 = Singleton01.getINSTANCE();
        System.out.println(instance1 == instance2);
        System.out.println("instance1.hashCode =" + instance1.hashCode());
        System.out.println("instance2.hashCode =" + instance2.hashCode());
    }
}

优缺点

长处:这种写法比较简单,就是在类装载的时候就实现实例化。防止了线程同步问题。

毛病:在类装载的时候就实现实例化,没有达到 Lazy Loading 的成果。如果从始至终从未应用过这个实例,则会造成内存的节约

这种形式基于 classloder 机制防止了多线程的同步问题,不过,instance 在类装载时就实例化,在单例模式中大多数都是调用 getInstance 办法,然而导致类装载的起因有很多种,因而不能确定有其余的形式(或者其余的静态方法)导致类装载,这时候初始化 instance 就没有达到 lazy loading 的成果

毁坏单例的情景
  • 反射毁坏单例:利用反射创立实例对象
  • 反序列化毁坏单例 :前提是实现了implements Serializable 接口
  • Unsafe 毁坏单例:这种情景是不能防止的
1、反射毁坏单例

利用反射获取类的构造方法

private static void reflection(Class<?> clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {Constructor<?> constructor = clazz.getDeclaredConstructor();
    constructor.setAccessible(true);
    System.out.println("反射创立实例:" + constructor.newInstance());
}

如何防止呢?

调用的时候加一层判断,如果创立了,则返回原实例或者抛出异样

private Singleton1() {if (INSTANCE != null) {throw new RuntimeException("单例对象不能反复创立");
    }
    System.out.println("private Singleton1()");
}
2、反序列化毁坏单例

通过对象输入流将对象转成为字节流,再通过 ByteArrayInputStream 办法将字节流转为对象

private static void serializable(Object instance) throws IOException, ClassNotFoundException {ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(instance);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    System.out.println("反序列化创立实例:" + ois.readObject());
}

如何防止呢?

// 办法名是固定的
public Object readResolve() {return INSTANCE;}
3、Unsafe 毁坏单例

通过反射调用 JDK 内置的 Unsafe 办法毁坏单例

private static void unsafe(Class<?> clazz) throws InstantiationException {Object o = UnsafeUtils.getUnsafe().allocateInstance(clazz);
    System.out.println("Unsafe 创立实例:" + o);
}

如何防止呢?

临时还没有找到解决的办法,大佬们晓得如何解决吗?

总结:这种单例模式可用,可能造成内存节约,启动就创建对象实例

2、饿汉式(动态代码块)

public class Singleton02 {

    private static final Singleton02 INSTANCE ;

    /**
     * 在动态代码块中,创立单例对象
     */
    static {INSTANCE = new Singleton02();
    }

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton02(){}

    /**
     * 提供一个私有的静态方法,返回实例对象
     * @return INSTANCE
     */
    public static Singleton02 getINSTANCE() {return INSTANCE;}

    public static void main(String[] args) {Singleton02 instance1 = Singleton02.getINSTANCE();
        Singleton02 instance2 = Singleton02.getINSTANCE();
        System.out.println(instance1 == instance2);
        System.out.println("instance1.hashCode =" + instance1.hashCode());
        System.out.println("instance2.hashCode =" + instance2.hashCode());
    }
}

优缺点

这种形式和下面的形式其实相似,只不过将类实例化的过程放在了动态代码块中,也是在类装载的时候,就执行动态代码块中的代码,初始化类的实例。优缺点和下面是一样的。

总结:这种单例模式可用,然而可能造成内存节约

3、懒汉式(线程不平安)

public class Singleton03 {

    private static Singleton03 INSTANCE ;

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton03(){}

    /**
     * 提供一个动态的私有办法,当应用到该办法时,才去创立 instance
     * @return INSTANCE
     */
    public static Singleton03 getINSTANCE() {if (INSTANCE == null) {INSTANCE = new Singleton03();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        // 模仿 1000 个线程拜访
        for (int i = 0; i < 1000; i++) {new Thread(new Runnable() {
                @Override
                public void run() {System.out.println("instance.hashCode=" + Singleton03.getINSTANCE().hashCode());
                }
            }).start();}
    }
}

优缺点

达到了 Lazy Loading 的成果,然而只能在单线程下应用。

如果在多线程下,一个线程进入了 if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可应用这种形式。

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

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

public class Singleton04 {

    private static Singleton04 INSTANCE ;

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton04(){}

    /**
     * 提供一个动态的私有办法,退出同步解决的代码,解决线程平安问题
     * @return INSTANCE
     */
    public static synchronized Singleton04 getINSTANCE() {if (INSTANCE == null) {INSTANCE = new Singleton04();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {for (int i = 0; i < 1000; i++) {new Thread(() ->{System.out.println("instance.hashCode=" + Singleton03.getINSTANCE().hashCode());
            }).start();}
    }
}

优缺点

解决了线程平安问题,给私有办法加上了锁

效率太低了,每个线程在想取得类的实例时候,执行 getInstance()办法都要进行同步。而其实这个办法只执行一次实例化代码就够了,前面的想取得该类实例,间接 return 就行了。办法进行同步效率太低

论断:在理论开发中,不举荐应用这种形式

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

public class Singleton05 {

    private static Singleton05 INSTANCE ;

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton05(){}

    /**
     * 提供一个动态的私有办法,退出同步解决的代码,解决线程平安问题
     * @return INSTANCE
     */
    public static Singleton05 getINSTANCE() {if (INSTANCE == null) {
            // 同步代码块
            synchronized (Singleton03.class){INSTANCE = new Singleton05();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {for (int i = 0; i < 1000; i++) {new Thread(() ->{System.out.println("instance.hashCode=" + Singleton03.getINSTANCE().hashCode());
            }).start();}
    }
}

优缺点

通过试图同步代码块来提高效率,解决线程平安

但事实上不可行,如果在多线程下,一个线程进入了 if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可应用这种形式。

6、双重查看

public class Singleton06 {

    private static volatile Singleton06 INSTANCE ;

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton06(){}

    /**
     * 提供一个动态的私有办法,退出双重查看代码,解决线程平安问题, 同时解决懒加载问题
     * @return INSTANCE
     */
    public static Singleton06 getINSTANCE() {if (INSTANCE == null) {
            // 同步代码块
            synchronized (Singleton03.class){if (INSTANCE == null) {INSTANCE = new Singleton06();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {for (int i = 0; i < 1000; i++) {new Thread(() ->{System.out.println("instance.hashCode=" + Singleton06.getINSTANCE().hashCode());
            }).start();}
    }
}

为何必须加 volatile:

  • INSTANCE = new Singleton4() 不是原子的,分成 3 步:创建对象、调用结构、给动态变量赋值,其中后两步可能被指令重排序优化,变成先赋值、再调用结构
  • 如果线程 1 先执行了赋值,线程 2 执行到第一个 INSTANCE == null 时发现 INSTANCE 曾经不为 null,此时就会返回一个未齐全结构的对象

优缺点

Double-Check 概念是多线程开发中常应用到的,如代码中所示,咱们进行了两次 if (singleton == null)查看,这样就能够保障线程平安了。

这样,实例化代码只用执行一次,前面再次拜访时,判断 if (singleton == null),间接 return 实例化对象,也防止的重复进行办法同步.

线程平安;提早加载;效率较高

总结:在理论开发中,举荐应用这种单例设计模式

7、动态外部类

public class Singleton07 {

    /**
     * 构造方法私有化,避免 new
     */
    private Singleton07(){}

    /**
     * 写一个动态外部类, 该类中有一个动态属性 Singleton
     */
    public static class SingletonClass{private static final Singleton07 INSTANCE = new Singleton07();
    }

    /**
     * 提供一个动态的私有办法,退出双重查看代码,解决线程平安问题, 同时解决懒加载问题
     * @return INSTANCE
     */
    public static Singleton07 getINSTANCE() {return SingletonClass.INSTANCE;}

    public static void main(String[] args) {for (int i = 0; i < 1000; i++) {new Thread(() ->{System.out.println("instance.hashCode=" + Singleton07.getINSTANCE().hashCode());
            }).start();}
    }
}

优缺点

这种形式采纳了类装载的机制来保障初始化实例时只有一个线程。

动态外部类形式在 Singleton 类被装载时并不会立刻实例化,而是在须要实例化时,调用 getInstance 办法,才会装载 SingletonClass 类,从而实现 Singleton 的实例化。

类的动态属性只会在第一次加载类的时候初始化,所以在这里,JVM 帮忙咱们保障了线程的安全性,在类进行初始化时,别的线程是无奈进入的。

长处:防止了线程不平安,利用动态外部类特点实现提早加载,效率高

论断:举荐应用

8、枚举

public enum Singleton08 {
    INSTANCE;

    public void sayHello(){System.out.println("你好,枚举单例模式!");
    }

    public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() ->{INSTANCE.sayHello();
                System.out.println("instance.hashCode ="+INSTANCE.hashCode());
            }).start();}
    }
}

优缺点

借助 JDK1.5 中增加的枚举来实现单例模式。不仅能防止多线程同步问题,而且还能避免反序列化从新创立新的对象,相对避免屡次实例化。

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

1、饿汉式

JDK 中,java.lang.Runtime 就是经典的单例模式(饿汉式)

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() {}
    
    ······
}

2、双检锁懒汉式单例

System 类中的 Console 对象的创立就是用的双重检锁

private static volatile Console cons = null;
/**
     * Returns the unique {@link java.io.Console Console} object associated
     * with the current Java virtual machine, if any.
     *
     * @return  The system console, if any, otherwise <tt>null</tt>.
     *
     * @since   1.6
     */
public static Console console() {if (cons == null) {synchronized (System.class) {if (cons == null) {cons = sun.misc.SharedSecrets.getJavaIOAccess().console();}
        }
    }
    return cons;
}

3、外部类懒汉式单例

Collections 类中的 ReverseComparator.REVERSE_ORDER 就是外部类懒汉式单例

private static class ReverseComparator
    implements Comparator<Comparable<Object>>, Serializable {

    private static final long serialVersionUID = 7207038068494060240L;

    static final ReverseComparator REVERSE_ORDER
        = new ReverseComparator();

    public int compare(Comparable<Object> c1, Comparable<Object> c2) {return c2.compareTo(c1);
    }

    private Object readResolve() { return Collections.reverseOrder(); }

    @Override
    public Comparator<Comparable<Object>> reversed() {return Comparator.naturalOrder();
    }
}

4、外部类懒汉式单例

Collections 中的 EmptyNavigableSet 就是外部类懒汉式单例

private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
    implements Serializable {
    private static final long serialVersionUID = -6291252904449939134L;

    public EmptyNavigableSet() {super(new TreeSet<E>());
    }

    private Object readResolve()        { return EMPTY_NAVIGABLE_SET;}
}

5、枚举饿汉式单例

Comparators.NaturalOrderComparator.INSTANCE 枚举饿汉式单例

class Comparators {private Comparators() {throw new AssertionError("no instances");
    }

    /**
     * Compares {@link Comparable} objects in natural order.
     *
     * @see Comparable
     */
    enum NaturalOrderComparator implements Comparator<Comparable<Object>> {
        INSTANCE;

        @Override
        public int compare(Comparable<Object> c1, Comparable<Object> c2) {return c1.compareTo(c2);
        }

        @Override
        public Comparator<Comparable<Object>> reversed() {return Comparator.reverseOrder();
        }
    }
    ......
}

4、注意事项和细节阐明

单例模式保障了零碎内存中该类只存在一个对象,节俭了系统资源,对于一些须要频繁创立销毁的对象,应用单例模式能够进步零碎性能。

当想实例化一个单例类的时候,必须要记住应用相应的获取对象的办法,而不是应用 new

单例模式应用的场景:

  • 须要频繁的进行创立和销毁的对象
  • 创建对象时耗时过多或消耗资源过多(即:重量级对象)
  • 但又常常用到的对象、工具类对象、频繁拜访数据库或文件的对象(比方数据源、session 工厂等)

5、总结

经验之谈:个别状况下,不倡议应用第 1 种和第 2 种懒汉形式,倡议应用第 3 种饿汉形式。只有在要明确实现 lazy loading 成果时,才会应用第 5 种注销形式。如果波及到反序列化创建对象时,能够尝试应用第 6 种枚举形式。如果有其余非凡的需要,能够思考应用第 4 种双检锁形式。

正文完
 0