Sometimes, there may be a need to have one and only one instance of a given class during the lifetime of an application.
A class that maintains its single instance nature by itself is referred to as a Singleton class.
Example
Use singolton FileLogger class to log messages to the file, because there is only one physical log file. In an application, when different client objects try to log messages to the file, there could potentially be multiple instances of the FileLogger class in use by each of the client objects.
This could lead to different issues due to the concurrent access to the same file by different objects.
- Make the Constructor Private : Making the constructor private prevents client objects from creating FileLogger objects by invoking its constructor. At the same time, other methods inside FileLogger will have access to the private constructor.
- Static Public Interface to Access an Instance : Provide a public interface, in the form of a static method FileLogger , for clients to be able to get access to an instance of the FileLogger class.
No comments:
Post a Comment