CHAPTER 3

image

Singleton Patterns

GoF Definition: Ensure a class only has one instance, and provide a global point of access to it.

Concept

A particular class should have only one instance. We will use only that instance whenever we are in need.

Real-Life Example

Suppose you are a member of a cricket team. And in a tournament your team is going to play against another team. As per the rules of the game, the captain of each side must go for a toss to decide which side will bat (or bowl) first. So, if your team does not have a captain, you need to elect someone as a captain first. And at the same time, your team cannot have more than one captain.

Computer ...

Get Java Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.