单利模式

来源:互联网 发布:下载源码的网站 编辑:程序博客网 时间:2024/04/30 13:37

单利模式是一个比较简单的模式,确保某一个类只有一个实例,并且自行实例化并向整个系统提供这个实例。他分为好几种写法,今天介绍三种单利模式。

一.饿汉式

public class Singleton {    /**     * 饿汉式     */    private static Singleton instance = new Singleton();    /**     * 私有的构造方法     */    private Singleton() {    }    /**     * 提供向外暴露获取实例的方法     *     * @return Singleton     */    public static Singleton getInstance() {        return instance;    }}

非线程安全,可能考虑到多线程并发的情况下,线程同步的问题。

二.懒汉式

public class Singleton {    /**     * 懒汉式     */    private static Singleton intance;    /**     * 私有构造方法     */    private Singleton() {    }    /**     * 提供当前类的对象     *     * @return 返回当前类     */    public static synchronized Singleton getIntance(){        if (intance == null) {            return intance = new Singleton();        }        return intance;    }}

三.双重检索

public class Singleton {    /**     * 双重检索模式     */    private static Singleton instance;    /**     * 私有构造方法     */    private Singleton() {    }    public static Singleton getInstance() {        if (instance == null) {            synchronized (Singleton.class) {                if (instance == null) {                    instance = new Singleton();                }            }        }        return instance;    }}

总结 .

单利模式的优点:
单利模式在内存中只有一个实例,减少了内存开销
减少了系统性能的开销,当对象产生需要比较多资源是,如读取配置,产生依赖对象时,则可以通过在应用启动直接产生。
单例模式可以避免对资源多重占用

单利模式的缺点:
单利模式没有接口,扩展困难,只能修改原来的代码。
单例模式没有完成不能够测试。
单利模式与单一原则有冲突。一个类只实现一个逻辑,不关心他是单利。