几种单例模式解析

1)单例模式的定义:数据库

在整个应用中,保证一个类只有一个实例,它提供了一个能够访问到它本身的全局访问点(静态方法)。安全

 

2)单例模式的优缺点:多线程

  优势:性能

  一、提供了对惟一实例的受控访问;spa

  二、Java中频繁建立和销毁类对象都会占用一部分系统资源,使用单例模式能够提升性能;线程

  三、容许可变数量的实例;设计

  缺点:code

  一、单例模式中,没有抽象层,因此对于单例类的扩展并不方便;对象

  二、单例类的职责太重,在必定程度上违背了“单一职责原则”;blog

  三、滥用单例将带来一些负面问题,如为了节省资源将数据库链接池对象设计为的单例类,可能会致使共享链接池对象的程序过多而出现链接池溢出;若是实例化的对象长时间不被利用,系统会认为是垃圾而被回收,这将致使对象状态的丢失;

3)简单介绍几种单例,单例模式中有区分了懒汉式和饿汉式,懒汉式主要是用时间来换空间,饿汉式则是用空间来换时间。饿汉式是线程安全的,懒汉式是非线程安全的,若是要实现懒汉式的非线程安全,则能够再访问点添加synchronized关键字声明便可。在其余的一些项目中还使用了双重检测枷锁机制。

  一、懒汉单例,存在线程不安全问题,如启动多线程,同时调用入口方法获取实例时不能正常工做:

//懒汉单例,线程不安全,当启动多线程,同时获取多个实例时会报错
   private static PostContentForResponse instance = null;
   private PostContentForResponse() {}
   public static PostContentForResponse getInstance() {
        if(instance == null) {
            instance = new PostContentForResponse();
        }
        return instance;
   }    

    懒汉模式也提供一种解决同步调用时不能正常工做的方法,使用synchronized声明访问点,可是工做效率低

   private static PostContentForResponse instance = null;
   private PostContentForResponse() {}
   public static synchronized PostContentForResponse getInstance() {
        if(instance == null) {
            instance = new PostContentForResponse();
        }
        return instance;
   }

   二、饿汉单例,这种方式基于classloder机制避免了多线程的同步问题,可是instance在类装载时就实例化,虽然致使类装载的缘由有不少种,

    在单例模式中大多数都是调用getInstance方法,可是也不能肯定有其余的方法(或者其余静态方法)致使类装载,这是初始化的instance

    显然没有达到lazy loading的效果。  

  private static PostContentForResponse instance = new PostContentForResonse();
 private PostContentForResponse() {}
 public static PostContentForResponse getInstance() {
     return instance;   
  }

   三、静态内部类,跟饿汉模式有点相似,只是在类装载的时候,SingletonHolder并无被主动使用,只有显式调用getInstance方法是,才会调用装载SingletoHolder类,从而实例化instance,既实现了线程安全,又避免了同步带来的性能影响。

  private static class SingletonHolder {
      private static final PostContentForResponse INSTANCE = new PostContentForResponse();
  }
  private PostContentForResponse() {}
  public static final PostContentForResponse getInstance() {
      return SingletonHolder.INSTANCE;
  }
相关文章
相关标签/搜索