The singleton pattern is probably one of the best-known design patterns. You have probably encountered many situations where you have an object that handles some centralized operation in your application, such as a logger
object. In such cases, it is usually preferred for only one such application-wide instance to exist and for all application code to have the ability to access it. Specifically, in a logger object, you would want every place in the application that wants to print something to the log to have access to it, and let the centralized logging mechanism handle the filtering of log messages according to log level settings. For this kind of situation, the singleton pattern exists.
Making your class a singleton class is usually done by implementing a static class method getInstance(), which returns the only single instance of the class. The first time you call this method, it creates an instance, saves it in
a private static variable, and returns you the instance. The subsequent times, it just returns you a handle to the already created instance.
object. In such cases, it is usually preferred for only one such application-wide instance to exist and for all application code to have the ability to access it. Specifically, in a logger object, you would want every place in the application that wants to print something to the log to have access to it, and let the centralized logging mechanism handle the filtering of log messages according to log level settings. For this kind of situation, the singleton pattern exists.
Making your class a singleton class is usually done by implementing a static class method getInstance(), which returns the only single instance of the class. The first time you call this method, it creates an instance, saves it in
a private static variable, and returns you the instance. The subsequent times, it just returns you a handle to the already created instance.