设计模式之单例模式
2021/7/16 23:11:02
本文主要是介绍设计模式之单例模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
设计模式
单例模式
懒汉模式
class Person{ /** * 单例模式设计 */ private String name; private int age; // 类字段 private static Person person = null; // 定义一个私有变量以提供唯一实例 private Person(){ } // 私有化构造方法 /** * 由于可能会有多线程访问,所以要锁 * @return Person的唯一实例 */ public static synchronized Person getInstance(){ if (person == null){ person = new Person(); } return person; } /** * 换个锁的位置保证效率 * @return person的唯一实例 */ public static Person getInstance2(){ if (person == null){ synchronized (Person.class){ if (person == null) { person = new Person(); } } } return person; } }
饿汉模式
class Student{ private static final Student STUDENT = new Student(); // 预实例化变量保存起来 private Student() { } // 私有化构造方法 /** * 直接返回,只读不需要考虑锁的问你 * @return Student的唯一实例 */ public static Student getInstance(){ return STUDENT; } }
总结
- 懒汉模式更节省内存,但是反之需要锁结构,会影响第一次访问时的效率
这篇关于设计模式之单例模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求