单例模式

2017-07-25  本文已影响0人  zxcvbnmzsedr

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

实现方式

单例模式分为两种,懒汉模式和饿汉模式。

懒汉模式

public class Singleton {
    private static Singleton instance;
    private Singleton (){}
    public static Singleton getInstance() {
     if (instance == null) {
         instance = new Singleton();
     }
     return instance;
    }
}

上面的代码在高并发情况下会创建多个实例,线程不安全。
解决方式:

  1. synchronized关键字
public static synchronized Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}
  1. 双重检查锁
    private static volatile Singleton INSTANCE = null;
    private Singleton() {}

    public static  Singleton getInstance() {
        if(INSTANCE == null){
             synchronized(Singleton.class){
                 if(INSTANCE == null){ 
                     INSTANCE = new Singleton();
                  }
              } 
        }
        return INSTANCE;
    }

饿汉模式

  public class Singleton {
    private final static Singleton INSTANCE = new Singleton();
  
    private Singleton() {}
 
    public static Singleton getInstance() {
        return INSTANCE;
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读