Introduction
Singletons ensure that a class only has one instance, and provide a global point of access to it.
Motivation
It is important for some classes to have exactly one instance. There should be only one dock manager for an application, there should be only one work bench for an application.
How do we ensure that a class has only one instance? A global variable makes an object accessible, but it doesn't keep you from creating multiple objects. For people who come from a C/C++ programming background, it is disturbing to find that C# does not support global variables.
Implementation
There are many ways to solve this problem and I will not go into them, but will explain a simple way of solving the problem by using a registry of singletons.
Most of the time, the solution will be a class that is written so that only one instance can be created. A common way to do this is to hide the operation that creates the instance behind a class operation that guarantees that only one instance is created.
Why a registry of singletons? Because an application will most of the time require more than just one type object which should be unique, therefore the need of a registry of singletons or a list of singletons used in the application
The registry maps between string names and singletons. When an instance needs a singleton, it consults theregistry, asking for the singleton by name.
Code
Collapse
|
Copy Code
using System;
using System.Collections;
namespace MySingleton
{
public class CSingleton
{
protected CSingleton(){}
static SortedList _register = new SortedList();
public static void Register(string name, ISingleton value)
{
if ( _register.ContainsKey(name))
throw new Exception("Key '" + name + "' already registered");
else
_register[name] = value;
}
public static ISingleton Lookup(string name)
{
return (ISingleton)_register[name];
}
}
public interface ISingleton
{
string Title
{
get;
set;
}
}
}
The idea is:
- To create an interface (
ISingleton
) that will be implemented by every class that needs to keep a singleton. E.g.:
Collapse
|
Copy Code
class A: ISingleton
{
public A() {}
}
class B: ISingleton
{
private string _greeting;
public B(string str){ _greeting = str;}
public string Greeting
{
get{ return _greeting;}
set{ _greeting = value;}
}
}
- To register the object with the singleton:
Collapse
|
Copy Code
CSingleton.Register("ClassA", (ISingleton) new A());
CSingleton.Register("ClassB", (ISingleton) new B("Hello"));
- To used the singleton object anywere in your code:
Collapse
|
Copy Code
A classAObj = (A) CSingleton.Lookup("ClassA");
B classBObj = (B) CSingleton.Lookup("ClassB");
classBObj.Greeting;
Conclusion
Hope this article will benefit you.