The Lazy Singleton Design Pattern in Java
- 时间:2020-09-25 11:32:47
- 分类:网络文摘
- 阅读:83 次
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) —
推荐阅读:营养专家建议的老年人健康饮食原则 绑架“第一口奶”该曝光的不仅是多美滋 汇源等多家国产果汁巨头卷入“烂果门” 两性营养保健:哪些食物让男人更持久 地沟油勾兑成调和油 检测仍无成熟技术 中医食疗:用蜂蜜治咳嗽,标本兼治! 常吃辛辣烫的食物易患消化道肿瘤 老年人可适当吃些零食保证营养需求 盘点网上那些错误的营养禁忌“神话” 食品科学博客解读网络盛传营养误区
- 评论列表
-
- 添加评论