What is a singleton?
It is design pattern that uses only one object or instance of an object at a time.
Steps to create a Singleton pattern
- Use getInstance() method as it is used universally for a singleton class
Example
Let’s take an example of Blackjack. In the game of blackjack, the dealer deals two cards to each player in the game. In the instance created would be the whole deck of cards that the dealer needs to deal. In this case, you would only need one instance of that class since you can only use one deck of cards. The game wouldn’t be fair if the dealer deals from different deck of cards for each player. So, once the dealer deals a card, that card will be removed from the list and the list contains the remaining cards to be dealt. Thats why a singleton class makes sense since you have to use the cards from only that instance. Check out the GitHub link for the code on this.