单例模式-基于headfirst设计模式的总结
程序员文章站
2022-06-19 15:02:56
1.经典的单例模式——懒汉式public class Singleton {private static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() {if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;} /...
1.经典的单例模式——懒汉式
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
主要的就是3步
1.创建静态私有变量
2.创建私有构造方法
3.创建静态方法返回对象
存在问题:线程不安全
2.饿汉式
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
}
线程安全,但是每次优先创建了对象消耗了多余的内存
3.加入同步代码块
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
影响了性能
4.双重检测法
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
用volatile来保证可见性
双重检测确保在对象为空的时候才创建对象,这样就可以减少每次对同步代码块的判断。
本文地址:https://blog.csdn.net/weixin_43484977/article/details/110261590
上一篇: 通过Python收集汇聚MySQL 表信息的实例详解
下一篇: python基础之类属性和实例属性