美文网首页
单例模式

单例模式

作者: helloKai | 来源:发表于2016-11-28 23:00 被阅读16次

单例模式的实现方式:

  • 构造函数私有

  • 通过静态方法或枚举返回对象

  • 多线程环境下也要保证单例对象只有一个

  • 单例对象在反序列化时不会重新构建

1 . 懒汉模式

public class Singleton {
    private static Singleton mInstance;

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }
}

缺点:每次调用都会消耗不必要的资源。
优点:只有在使用的时候才会实例化。
建议:不建议使用。

2 . 饿汉模式

public class Singleton {
    private static Singleton mInstance = new Singleton();

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        return mInstance;
    }
}

3 . DCL(Double Check Lock)

public class Singleton {
    private volatile static Singleton mInstance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (mInstance == null) {
            synchronized (Singleton.class) {
                if (mInstance == null) {
                    mInstance = new Singleton();
                }
            }
        }
        return mInstance;
    }
}

优点:第一次执行时才会实例化,效率高。
缺点:第一次加载慢。
建议:推荐的使用方式。

4 . 方法的改进模式

public class Singleton {
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.mInstance;
    }

    private static class SingletonHolder {
        private static final Singleton mInstance = new Singleton();
    }
}

建议:比之前三种都要好,推荐的使用方式。

相关文章

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • 单例模式

    单例模式1 单例模式2

  • java的单例模式

    饿汉单例模式 懒汉单例模式

网友评论

      本文标题:单例模式

      本文链接:https://www.haomeiwen.com/subject/xlfapttx.html