单例
- 有些对象只需要有一个: 线程池、缓存、注册表,这类对象只能有一个实例,如果制造多个实例,就会导致许多问题的产生,比如,程序的行为异常、资源使用过量,或者不一致;
- 全局变量的缺点:如果将对象赋值给一个全局变量,那么在程序一开始就要创建好对象,如果对象比较耗费资源,而程序在执行过程中一直没有用到,就浪费了。
单例模式的定义:确保一个类只有一个实例,并提供一个全局访问点,可以延迟实例化。适用于对资源敏感的对象 。
package Singleton;
/**
* Created by coo on 17/12/2.
* 注意:不适用于多线程的情形
*/
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){};
public static Singleton getInstance(){
if (uniqueInstance == null) { // Thread 1、Thread 2 可能先后进入这个方法,导致产生两个不同的object;
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
// multi Thread synchronized
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){};
public static synchronized Singleton getInstance(){
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
缺点:每次调用该方法都会进行同步,性能不好;
/**
* Created by liuchaoqun01 on 17/12/2.
* 急切实例化
*/
public class Singleton {
// jvm 初始化类的时候静态加载,保证线程安全
private static Singleton uniqueInstance = new Singleton();
private Singleton(){};
public static Singleton getInstance() {
return uniqueInstance;
}
}
双重检查加锁模式 java1.5以后适用:
public class Singleton {
private volatile static Singleton _instance;
private Singleton(){};
public static Singleton getInstanceDC() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
}