单例模式
简介:
- 单例模式就是一个类只有一个实例。需满足条件如下:
- 通过 static 关键字确保类只有唯一实例
- 类的构造函数需要私有化,确保外部不能调用构造函数创建实例
- 类通过静态方法或者静态变量为外部访问唯一实例提供入口
实现方法
饿汉模式
public class Singleton{
private static Singleton instence = new Singleton();
private Singleton(){};
public static Singleton getInstence(){
return instence;
}
}
懒汉模式(非线程安全)
public class Singleton{
private static Singleton instence = null;
private Singleton(){};
public static Singleton getInstence(){
//多线程时候会出现线程安全问题,
//因为是单例模式使用static修饰只能为一个实例
if (instence == null){
return new Singleton();
}
}
}
懒汉模式(线程安全)
public class Singleton{
private static Singleton instence = null;
private Singleton(){};
public static Singleton getInstence(){
if (instence == null){//减少锁开销,如果存在不加锁
synchronized(Singleton.class){
if (instence == null){//当线程1释放锁后,单例已存在,防止线程2获取锁继续创建,然后出现static修饰变量两次实例化申请空间
return new Singleton();
}
}
}
}
}
静态内部类模式
public class Singleton{
private Singleton(){};
private static class SingletonHolder{
private static Singleton instence = new Singleton();
}
public Static Singleton getInstence(){
return SingletonHolder.instence;
}
}
参考文档:单例模式