Learn the Singleton Design Pattern

Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.

UML Class Diagram

Not familiar with UML Class Diagram? I have written a detailed post on the UML Class diagram.

Implementation steps:

Using Binary Semaphore

// Output on my system
pool-1-thread-2: Instance is null before acquiring semaphore
pool-1-thread-2: Semaphore acquired
pool-1-thread-1: Instance is null before acquiring semaphore
pool-1-thread-2: Instance is null after acquiring semaphore
pool-1-thread-2: Semaphore released
pool-1-thread-2: You are testing Singleton Class: 1258930662
pool-1-thread-1: Semaphore acquired
pool-1-thread-1: Semaphore released
pool-1-thread-1: You are testing Singleton Class: 1258930662

Using Synchronized

// Output on my system
pool-1-thread-2: Instance is null before synchronized
pool-1-thread-1: Instance is null before synchronized
pool-1-thread-2: Instance is null after synchronized
pool-1-thread-2: You are testing Singleton Class: 1962484795
pool-1-thread-1: You are testing Singleton Class: 1962484795

Using enum to create Singleton

// Output on my system
pool-1-thread-2: You are testing Singleton Class: 1962484795
pool-1-thread-1: You are testing Singleton Class: 1962484795

Pros of Singleton design pattern

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store