The Lazy Singleton Design Pattern in Java

  • 时间:2020-09-25 11:32:47
  • 分类:网络文摘
  • 阅读:125 次

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;
    }
}
2091E060-120E-4C44-BAA3-7E4E0DF7BD55 The Lazy Singleton Design Pattern in Java design pattern design questions java

Java

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
大暑养生:暑天应多吃清淡易消化食物  市场热俏的功能性饮料到底是什么?  不能把功能性饮料完全代替饮用水  功能性饮料应该如何科学合理的饮用  网传的10种致癌食物中有9种不靠谱  夏季常见水果:西瓜的营养保健价值  健康食品黑枣的食疗功效与营养价值  保健食品当做药品卖“脑力风暴”骗局  “公益网站”牵线 保健食品当药品卖  消费者如何正确选择购买保健食品 
评论列表
添加评论