美文网首页
单例模式常用方式

单例模式常用方式

作者: 陈陈_04d0 | 来源:发表于2020-12-01 16:07 被阅读0次

1、懒汉式  单线程方便,但是多线程不安全

public class Test{

public Test  test;

public static Test  getInstance() {

    if (instance == null) { 

        test= new Test (); 

    } 

    return test; 

    } 

}

2、懒汉式 线程安全版

public class Test{

    private static Test test; 

    public static synchronized Test getInstance() { 

    if (test== null) { 

        test = new Test(); 

    } 

    return test; 

    }  

}

3、饿汉式 线程安全,效率高,但是类创建就初始化对象,容易浪费内存

public class Test{

private static Test tes=new Test();

public static synchronized Test getInstance() {

return test;

    }  

}

4、双重验证方式  采用双锁机制,安全且在多线程情况下能保持高性能。

public class Test {

private static Testtest;

    public static TestgetSingleton() {

if (test ==null)

synchronized (Test.class) {

if (test ==null)

test =new Test();

   }

return test;

    }

}

总结:一般优先选择第三种方式,特殊情况可以选择第四种。

相关文章

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

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

  • 【设计模式】单例模式

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

  • 创建单例模式(Singleton)的几种方式

    单例模式可能是最常用到的设计模式了,但是想要正确的使用单例模式却并不简单。 我们先从最简单最常用的方式开始: 转自...

  • 单例模式汇总

    Java单例模式 java单例模式是为了让全局只实例化一个对象,常用的方式包括懒汉模式、饿汉模式,考虑到线程安全,...

  • 单例模式常用方式

    1、懒汉式 单线程方便,但是多线程不安全 public class Test{ publicTest test; ...

  • Node.js与单例模式

    1、前端的JavaScript单例模式 单例模式是非常常用的设计模式,前端的JavaScript中单例模式代码可能...

  • java中单例模式实现(包含double-check)

    单例模式是24中设计模式中的最常用、也是最为简单的一种设计模式。java中实现单例模式的方式,大致分为两种: 1、...

  • IOS学习笔记之单例

    单例介绍 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一种常用的软件设计模...

  • 设计模式--单例模式

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

  • 设计模式总结

    常用设计模式 1.单例设计模式 单例设计模式分为两种方式:懒汉式和恶汉式 恶汉式:加载源代码的时候就已经创建了对象...

网友评论

      本文标题:单例模式常用方式

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