美文网首页
单例模式 - 5种实现方式

单例模式 - 5种实现方式

作者: 成长和自由之路 | 来源:发表于2017-09-26 15:58 被阅读0次

1、饿汉。线程安全,类装载时就实例化。

public class SingleInstance {

    private SingleInstance(){}

    private static SingleInstance mSingleInstance = new SingleInstance();

    public static SingleInstance getInstance(){
        return mSingleInstance;
    }

}

2、懒汉。懒加载,效率较低。

public class SingleInstance {

    private SingleInstance(){}

    private static SingleInstance mSingleInstance;

    public static synchronized SingleInstance getInstance(){
        if (mSingleInstance == null) {
            mSingleInstance = new SingleInstance();
        }
        return mSingleInstance;
    }
}

3、双重校验锁。使用volatile变量,轻量级的同步机制。

public class SingleInstance {

    private SingleInstance(){}

    private volatile static SingleInstance mSingleInstance;

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

4、静态内部类

public class SingleInstance {

    private SingleInstance(){}

    public static SingleInstance getInstance(){
        return SingleHolder.instance;
    }

    private static class SingleHolder {
        private static SingleInstance instance = new SingleInstance();
    }

}

5、枚举

public enum SingleInstance {
    INSTANCE;
}

相关文章

  • 单例模式的常用实现方式

    单例模式属于最常用的设计模式,Java中有很多实现单例模式的方式,各有其优缺点 实现方式对比 单例实现方式线程安全...

  • 设计模式--单例模式

    单例模式概述 单例模式实现方式 为什么要使用单例模式 单例模式实现方式 饿汉式 类加载后就会将对象加载到内存中,保...

  • kotlin实现单例模式

    1.懒汉式实现单例模式 2.线程安全懒汉式实现单例模式 3.双重校验懒汉式实现单例模式 4.静态内部类方式实现单例模式

  • Python经典面试题21道

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python最经典面试题21道,必看!

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python 经典面试题

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • Python 经典面试题

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

  • 单例模式(Singleton)- 通俗易懂的设计模式解析

    单例模式的实现方式单例模式的实现方式有多种,根据需求场景,可分为2大类、6种实现方式。具体如下: a. 初始化单例...

  • 单例模式

    什么是单例模式? 一个类只允许创建一个实例,那个类就是单例类。这个模式就是单例模式。单例模式实现方式:饿汉式:实现...

  • 2018-06-19 Python中的单例模式的几种实现方式的及

    转载自: Python中的单例模式的几种实现方式的及优化 单例模式 单例模式(Singleton Pattern)...

网友评论

      本文标题:单例模式 - 5种实现方式

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