设计模式之单例模式
来源:互联网 发布:plc仿真软件 编辑:程序博客网 时间:2024/06/07 19:50
1.定义
顾名思义,单例模式就是无论你有多少次创建,全局只能有一个该对象的实例
2.单例的几种写法
个人比较了解的有七种写法:
public class Singleton01 { private Singleton01(){} private static Singleton01 instance =new Singleton01(); // 类被加载的时候就被初始化了,导致不必要的资源的浪费和时间的浪费 public static Singleton01 getInstance(){ return instance; }}public class Singleton02 { private Singleton02(){} private static Singleton02 instance; public static Singleton02 getInstance(){ if(instance == null){//多线程不安全,多个线程同时访问 不能保证单例 instance = new Singleton02(); } return instance; }}public class Singleton03 { private Singleton03(){} private static Singleton03 instance; public synchronized static Singleton03 getInstance(){//能保证单例,但是太耗费资源,每次都要去获取整个对象的锁 if(instance == null){ instance = new Singleton03(); } return instance; }}public class Singleton04 {//DCL private Singleton04(){} private static Singleton04 instance; public static Singleton04 getInstance(){ if(instance == null){ synchronized (Singleton04.class) { if(instance == null){ instance = new Singleton04();//出现内存的重排序 内存指向内存分配的地址,但是没有当前对象的引用,导致线程2进来时instance已经不为空 } } } return instance; }}public class Singleton05 { private Singleton05(){} private volatile static Singleton05 instance;//不会出现内存重排序的,此关键字在内存中加入指令设置屏障,在写入副本时同时也刷新内存,这样导致副本和内存的数据一致 public static Singleton05 getInstance(){ if(instance == null){ synchronized (Singleton05.class) { if(instance == null){ instance = new Singleton05(); } } } return instance; }}public class Singleton06 { private Singleton06(){} private static class InnerClass{ private final static Singleton06 instance = new Singleton06();//内部类的实现方式,比较优雅,在想初始化的时候初始化,又能保证线程的安全,反序列化的时候不能保证单例 } public static Singleton06 getInstance(){ return InnerClass.instance; }}public enum Singleton07 { INSTANCE;//能够保证单例,并且在反序列化的时候也能够保证是单例的 private A instance; private Singleton07(){ instance = new A(); } public A getInstance(){ return instance; }}
3.单例模式的优缺点
优点:
1.全局只有一个实例,方便管理。
2.因为全局只有一个实例,可以节约资源,对于一些频繁创建和销毁资源的对象来说,这样大大的减少了资源的消耗。
3.可以允许生命的实例数。
缺点:
1.单例模式一般没有接口或者抽象类,不方便扩展,只能在代码中修改扩展。
2.对于持有的上下文为context时,非常容易造成内存泄漏,导致资源一直被占用。建议用applcationContext。
把自己学习设计模式的过程记成笔记,方便自己随时查看,如有错误,欢迎指出,谢谢!
阅读全文
1 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- cassandra节点异常:java.lang.OutOfMemoryError: Direct buffer memory
- 51nod 1804 小C的多边形(贪心)
- 词向量源码解析:(4.5)hyperwords源码解析之representations
- RPGMakerMV的插件学习
- STM32再学习——启动流程分析
- 设计模式之单例模式
- Spring boot系列:配置文件(二)
- Maven 之 加载本地的jar包
- 控制循环结构(break、continue)、return结束方法
- leetcode 133. Clone Graph
- 配置处理结果
- 评职称自费出书多少钱
- mybatis-plus使用要注意的事项
- LeetCode-Longest Palindromic Substring