Sometime in programming we need to have only one instance of object for example in logger class.
Such type of situation in programming is mostly handled by Singleton Classes.
Singleton is a software design pattern which ensures only one object of a type is created. This is useful when we want to create an object, which manages or coordinates some tasks in the system. A WindowManager, a FileSystem, Mouse Pointer would be good examples for places where Singleton design pattern can be applied.
The singleton pattern is one of the simplest design patterns it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.
How To follow Singleton programming Pattern
- Make sure class can't create more than one variable
- Provide a global access to that instance
Implementation
- Singleton class have a private constructor which restricts programmers to create instance of the class.
- Singleton class also have a static method and a private variable of the Singleton class type, this private variable used to hold the single instance of the class.
- Static method is used to expose the private variable.
class MySingletonClass
{
private static MySingletonClass instance;
private MySingletonClass()
{
...
}
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new MySingletonClass();
return instance;
}
...
public void doSomething()
{
...
}
public void doSomethingElse()
{
...
}
}
Uses Of Singleton Pattern
- Logger Class
- Configuration Class
- Centralized Coordination of task
Profit
- Single instance save memory which is very important for low memory devices
- Simple accessibility of shared Resource
Note :-
To keep things simple, above implementation not Support Multithreaded programs. If you are curious and know about multithreaded programming than i am sure you also know that "Locking the Methods" is the way.
No comments:
Post a Comment