Singleton Design Pattern
In Software Engineering Singleton pattern restricts from creating more than one object of class.
Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples.
Some familiar examples that we see everyday are
Logger
We use logger to log info, debug and error messages throughout application. In this we do not need to create multiple instances of logger. Only one instance can serve this purpose. If you go through LoggerFactory class then you will find that it is singleton class which every time gives the same object.
Singleton objects are like utility, so they require global point of access.
The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:
- Ensure that only one instance of a class is created
- Provide a global point of access to the object
One very common and most efficient example is
Spring MVC
In Spring MVC bean creation is very common. You should know that there are some scopes to beans
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request. *
session – Return a single bean instance per HTTP session. *
globalSession – Return a single bean instance per global HTTP session. *
By default Spring MVC uses singleton scope for beans. So most of the time unknowingly you are dealing with singleton bean objects. This saves lot of memory and makes spring light and efficient framework.
Singleton Java Implementation
In Java programming you need few things to write a singleton class
private constructor
You need to make your constructor private so that instances from outside can not be created.
static method to return first time created instance
Okay so someone can not create instance from outside. Now you need to crate instance first time and pass it. You need a static method that can be called without creating object.
final class
It is not compulsory to make your class behave as singleton. But if you will make your class final then it will restrict to modification of your singleton class.
Java Singleton Code Example
public class MySingleton {
private static MySingleton instance = null;
// Private Constructor
private MySingleton() {
// Exists only to defeat instantiation.
}
// static method to return instance
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
This singleton example is easy to understand. We call it Classic Singleton.
0 Comments
Post a Comment