美文网首页
23种设计模式-单例模式

23种设计模式-单例模式

作者: 王灵 | 来源:发表于2019-03-02 22:09 被阅读0次

定义:确保某个类只有一个实例,且自行实例化并为整个系统提供这个实例。
作用:在前提条件下,使对象只具有唯一实例。
实现方式

  • 饿汉模式
//缺点是不管使不使用都会被创建实例
public class Singleton {
    private static Singleton singleton = new Singleton();

    public static Singleton getInstance() {
        return singleton;
    }
}
  • 懒汉模式
public class Singleton {
    private static Singleton singleton = null;

    private Singleton() {
    }

    /**
     * 在多线程情况下使用synchronized了会导致访问受限
     * 如果不使用synchronized 可能会导致生成多个实例,不能保证线程安全
     * 优点是需要时才创建
     * @return
     */
    public static synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}
  • DCL
public class Singleton {
    private static Singleton singleton = null;

    private Singleton() {
    }

    /**
     * 优点:即是在需要时加载,也解决了多线程安全的问题
     * 缺点:由于编译器优化了程序指令, 允许对象在构造函数未调用完前, 将共享变量的引用指向部分构造的对象, 虽然对象未完全实例化, 但已经不为null了.DCL失效
     *
     * @return
     */
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
  • 静态内部类单例
public class Singleton {
    private Singleton() {  }
    /**
     * 由于第一次加载Singleton类时并不会初始化sInstance,只有在第一次调用Singleton.getInstance方法时才会导致sInstance被初始化
     * @return
     */
    public static  Singleton getInstance() {
        return SingletonHolder.sInstance;
    }
    static class SingletonHolder{
      static final   Singleton sInstance=new Singleton();
    }
}

相关文章

  • 单例模式Java篇

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

  • python中OOP的单例

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

  • 单例

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

  • 设计模式 - 单例模式

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

  • 设计模式

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

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

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

  • python 单例

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

  • 基础设计模式:单例模式+工厂模式+注册树模式

    基础设计模式:单例模式+工厂模式+注册树模式 单例模式: 通过提供自身共享实例的访问,单例设计模式用于限制特定对象...

  • 单例模式

    JAVA设计模式之单例模式 十种常用的设计模式 概念: java中单例模式是一种常见的设计模式,单例模式的写法...

  • 设计模式之单例模式

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

网友评论

      本文标题:23种设计模式-单例模式

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