设计模式之单例模式

147 阅读1分钟

单例模式,故名思意,在应用程序生命周期内一个类只有对应的一个实例。维基百科的定义如下

单例模式,也叫单子模式,是一种常用的软件设计模式。在应用这个模式时,单例对象的必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。

实现方式也很简单,构造函数私有化,通过一个静态的方法或者属性获取该类唯一实现即可。唯一要注意的就是在多线程下需要保证只生成一个实例。

  1. 饿汉模式
public class Singleton {  
     private static Singleton instance = new Singleton();  
     private Singleton (){
     }
     public static Singleton getInstance() {  
     return instance;  
     }  
 } 
  1. 懒汉模式(线程不安全)
ublic class Singleton {  
      private static Singleton instance;  
      private Singleton (){
      }   
      public static Singleton getInstance() {  
      if (instance == null) {  
          instance = new Singleton();  
      }  
      return instance;  
      }  
 }  
  1. 双重检查模式(此模式使用较多)
public class Singleton {  
      private  static Singleton singleton;  
  private static Object _lock = new Object();
      private Singleton (){
      }   
      public static Singleton getInstance() {  
      if (instance== null) {  
          lock (_lock) {  
          if (instance== null) {  
              instance= new Singleton();  
          }  
         }  
     }  
     return singleton;  
     }  
 }  
  1. 静态内部类(不支持传参)
public class Singleton { 
    private Singleton(){
    }
      public static Singleton getInstance(){  
        return SingletonHolder.sInstance;  
    }  
    private static class SingletonHolder {  
        private static final Singleton sInstance = new Singleton();  
    }  
}