什么是单例模式
单例模式:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个
这个类称为单例类,它提供全局访问方法。
代码
//单例类
public class LoadBalancer {
//私有成员变量,只保证存在一个实例
private static LoadBalancer instance=null;
//构造函数私有化,这样保证了,其他类不能实例化该类
private LoadBalancer()
{
}
//公有成员方法, 创建实例,并保证该实例只存在一个
public static LoadBalancer getInstance()
{
if(instance==null)
{
instance=new LoadBalancer();
}
return instance;
}
}
造成的问题
LoadBalancer l1=LoadBalancer.getInstance();
LoadBalancer l2=LoadBalancer.getInstance();
即如果这个构造函数很大,当第一次调用getInstance()方法时,此时instance为null,,进行instance=new LoadBalancer();,在此过程中进行大量的初始化工作,在这个过程中如果再来一次调用getInstance()方法,而此时由于instance未创建成功if通过,所以会再次执行instance=new LoadBalancer();。
解决方法:饿汉式单例和懒汉式单例
饿汉式单例
直接在定义静态变量的时候就实例化单例类
public class EagerSingleton {
//在定义静态变量时初始化,由于静态变量是在类装载时进行,故在这时候instance就建立好了故
//不会出现两次建立
private static EagerSingleton instance=new EagerSingleton();
private EagerSingleton()
{
}
public static EagerSingleton getInstance()
{
return instance;
}
}
懒汉式单例
在getInstance();时进行判断是否为单例,达到延迟加载。
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() {
}
// 第一种锁
// 这种情况下 如果线程多时会影响效率
/*
* synchronized public static LazySingleton getInstance(){
* if(instance==null) {
* instance=new LazySingleton();
* }
* return instance;
* }
*/
// 第二种锁
//这种A和B线程同时调用该方法仍会得到两个实例
/*
public static LazySingleton getInstance() {
if (instance == null) {
//锁定代码块
synchronized (LazySingleton.class) {
instance = new LazySingleton();
}
}
return instance;
}
*/
//第三种锁 :双重锁
public static LazySingleton getInstance() {
//一重判断
if (instance == null) {
//锁定代码块
synchronized (LazySingleton.class) {
//二重判断
if (instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
}