Singleton pattern

The singleton pattern is used to restrict the creation of only object of a class. This is useful when it is expensive (in terms of resources) to initiate new objects every time the same object is needed. This pattern specifically put this logic of maintaining only one instance inside the class itself.

This pattern can be used in situations like database connectivity, reading and writing to disk, sending emails.

In the example below we use a simple translation class which read a json file with translations. Only one instance is needed since reading file operations are slower. Therefore we can easily use this object as many times as needed for multiple words translation. Since it is a singleton so it will keep only one instance each time we use it in the code.