美文网首页
单例设计模式

单例设计模式

作者: 少一点 | 来源:发表于2017-08-08 11:49 被阅读0次

1.懒汉式 线程不安全,当有多个线程并行调用getInstance()的时候,就会创建多个实例。也就是说在多线程下不能正常工作。

public class Singleton{

private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){

if(instance == null){

instance = new Singleton();

    }

return instance;

}

}

2.懒汉式 线程安全,虽然做到了线程安全,并且解决了多实例的问题,但是它并不高效。因为在任何时候只能有一个线程调用getInstance()方法。但是同步操作只需要在第一次调用时才被需要,即第一次创建单例实例对象时。这就引出了双重检验锁。

public class Singleton{

private static Singleton instance;

private Singleton(){}

public synchronized static Singleton getInstance(){

if(instance == null){

instance = new Singleton();

}

return instance;

}

}

3.双重检验锁

public static Singleton getSingleton() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

}

}

}

return instance ;

}

>改进代码, instance 变量声明成 volatile

public class Singleton {

private volatile static Singleton instance; //声明成 volatile

private Singleton (){}

public static Singleton getSingleton() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

}

}

}

return instance;

}

}

4.饿汉式,在第一次加载类到内存中时就会初始化,所以创建实例本身是线程安全的。

public class Singleton {

//类加载的时候就初始化

private static final Singleton instance =  new Singleton();

private Singleton(){}

public static Singleton getInstance() {

return instance;

}

}

5.静态内部类.

public class Singleton {

private static class SingletonHolder{

private static final INCTANCE = new Singleton();

}

private Singleton(){}

public static final Singleton getInstance(){

return SingletonHolder.INSTANCE;

}

}

6.枚举

public enum EasySingleton {

INSTANCE;

}

相关文章

  • 单例模式Java篇

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

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

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

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

  • 设计模式第二篇、单例设计模式

    目录1、什么是单例设计模式2、单例设计模式的简单实现3、单例设计模式面临的两个问题及其完整实现4、单例设计模式的应...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 2、创建型设计模式-单例设计模式

    江湖传言里的设计模式-单例设计模式 简介:什么是单例设计模式和应用 备注:面试重点考查 单例设计模式:这个是最简单...

  • 设计模式之单例模式

    单例设计模式全解析 在学习设计模式时,单例设计模式应该是学习的第一个设计模式,单例设计模式也是“公认”最简单的设计...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

网友评论

      本文标题:单例设计模式

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