Thursday, January 21, 2010
Singleton Pattern (Creational)
1/21/2010 11:58:00 PM |
Posted by
VijayKumar Yadavalli
|
Edit Post
AIM:
Restrict instantiation of a class to one object and provide a global point of access to the object.
Class Diagram:
Participants:
The classes and/or objects in this pattern are
Singleton(EmailManager)
- defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
responsible for creating and maintaining its own unique instance.
public sealed class EmailManager
{
private static EmailManager _manager;
private static object forLock = new object();
//Private constructor so that objects cannot be created
private EmailManager()
{
}
public static EmailManager Instance()
{
// Use 'Lazy initialization'
if (_manager == null)
{
//ensure thread safety using locks
lock(typeof(forLock))
{
_manager = new EmailManager();
}
}
return _manager;
}
}
When should use it
Singleton should be used in cases where only one object is needed to coordinate actions and/or events across the application;
The application will always use the object in the same way;
It doesn’t really matter to the client what’s going on in the rest of the application, meaning that the singleton object is independent.
Another question that usually comes up when it comes to using a Singleton is “Why not just use a static class?”. Static classes still have many uses and lots of times, people get confused and will use a Singleton as much as possible. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.
So here is a quick list of uses for static classes: Math.pow(double a, double b);
Interger.parseInt(String s);
Interger.toString(int i);
As you can see, the state of these methods doesn’t matter. You just want to use them to perform a simple task for you. But if you coding your application and you are using a central object where state does matter, then its best to use a Singleton.
The next reason you may want to use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, you probably only one of those objects floating around. This is the case for things like a if you have a factory method that is particularly robust, you want to make sure that it’s not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening.
Examples
Logging classes
Configuration classes
Accessing resources in shared mode
Factories implemented as singletons
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment