Singleton Design Pattern

1. Introduction

Let's try and understand Singleton design pattern.
Note: We will be using Spring Boot for all code examples, there is no reason for it, it's just the way we code :)

By Definition, singleton class is one which will have exactly one instance of the class at any given point of time in the given container ( JVM or so).

2. Implementation

Let's try to implement the class.

2.1 Eager Implementation




















2.2 LazyLoad Implementation

Let's delay the class creation until accessed :




















However, this class has one flaw, can you spot?
It is not thread safe.

2.3 LazyLoad Threadsafe

Let's make class (instance creation) thread safe:






















2.4 LazyLoad Threadsafe - improved version


























2.5 LazyLoad Using Helper class






















2.6 LazyLoad Using Enum














2.6 Singleton & Serializable 



























The code is availble in github, enjoy design-patterning :) 




No comments:

Post a Comment