什么是单例模式?
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
单例模式的特点?
①、单例类只能有一个实例
②、单例类必须自己创建自己的唯一实例
③、单例类必须给所有其他对象提供这一实例
单例模式的分类(饿汉和懒汉):
饿汉模式
饿汉模式:主动去找食物,一开始就吃掉。
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
//getInstance是获取单例对象的方法,
return instance;
}
}
懒汉模式-等着人去喂食物(单例的初始值为空,还未构建)
懒汉模式-单线程版
public class Singleton {
private Singleton() {} //私有构造函数:.要想让一个类只能构建一个对象,自然不能让它随便去做new操作,因此Signleton的构造方法是私有的
private static Singleton instance = null; //单例对象
//静态工厂方法
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉模式-多线程版-性能低
class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public synchronized static Singleto getInstance() {//为了防止new Singleton被执行多次,因此在new操作之前加上Synchronized 同步锁,锁住整个类
if(instance==null){
instance = new Singleton();
}
return instance;
}
}
懒汉模式-多线程版-二次判断-性能高
class Singleton {
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;
}
}