The Lazy Singleton Design Pattern in Java
- 时间:2020-09-25 11:32:47
- 分类:网络文摘
- 阅读:123 次
The Singleton design is one of the must-known design pattern if you prepare for your technical interviews (Big IT companies have design questions apart from coding questions). The Singleton Pattern allow one class to have only one instance at any time. You can delay the instantiation to the point when it is needed for the first time.
Below shows the Lazy Singleton Design Pattern in Java. We use the keyword volatile to tell the Java (Java Virtual Machine) that at any time, reading the member field should be made directly from/to the memory location i.e. no cache should be used.
And We need to define the private constructor to avoid external instantiation via the constructor.
Lastly, the syncrhonized keyword in Java solves the racing conditions if multithreading access occurs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.company.singleton; public class LazySingleton { // the instance will not be cached private static volatile LazySingleton instance = null; // private constructor - avoid Instantiation private LazySingleton() { } public static synchronized LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } } |
package com.company.singleton;
public class LazySingleton {
// the instance will not be cached
private static volatile LazySingleton instance = null;
// private constructor - avoid Instantiation
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
Java
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:数学题:9个队员进行单循环制猜丁壳比赛 数学题:有三位登山者要攀登一座荒无人烟的大山。出发时每人只能携带够6天的食物 数学题:一个多位数四舍五入后是1亿,这个数最小是多少? 新网站优化对于一个企业来说到底有多重要 大学生如何在渗透测试行业立足 网站渗透测试中的历程经验记录分析 百度推出的“鸿雁计划”到底有什么用?对站长有哪些影响? 如何构建高质量的网站? 2020年SEO优化应该注意哪些细节?新手必看 运营笔记:花5分钟看完这篇文章,保证让你立马学会写运营方案
- 评论列表
-
- 添加评论