Click here to Skip to main content
Licence CPOL
First Posted 6 Jan 2004
Views 44,093
Downloads 25
Bookmarked 11 times

Registry of Singletons

By | 6 Jan 2004 | Article
Desgin Patterns - Object creation - Singleton.

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 the registry, asking for the singleton by name.

Code

using System; 
using System.Collections;
namespace MySingleton
{
    /// <summary> 
    /// Summary description for CSingleton. 
    /// </summary>
    public class CSingleton 
    {
        protected CSingleton(){} 
        static SortedList _register = new SortedList();
        public static void Register(string name, ISingleton value) 
        {
            // Cannot overwrite a key 
            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;
        }
    }
} //~Namespace

The idea is:

  1. To create an interface (ISingleton) that will be implemented by every class that needs to keep a singleton. E.g.:
  2. 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;}
        }
    }
  3. To register the object with the singleton:
  4. CSingleton.Register("ClassA", (ISingleton) new A());
    CSingleton.Register("ClassB", (ISingleton) new B("Hello"));
  5. To used the singleton object anywere in your code:
  6. A classAObj = (A) CSingleton.Lookup("ClassA");
    B classBObj = (B) CSingleton.Lookup("ClassB");
    classBObj.Greeting;

Conclusion

Hope this article will benefit you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Guy Baseke

Software Developer (Senior)

Canada Canada

Member

Software engineer

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralAnother reason why this is bad Pinmemberdog_spawn8:02 8 Jan '04  
GeneralUnnecessary PinmemberRichLee22:55 7 Jan '04  
GeneralRe: Unnecessary PinmemberJörgen Sigvardsson23:22 7 Jan '04  
GeneralRe: Unnecessary PinmemberRichLee23:39 7 Jan '04  
GeneralRe: Unnecessary PinmemberMcGiv23:26 7 Jan '04  
GeneralAn alternative solution PinmemberMidnight14:41 7 Jan '04  
GeneralRe: An alternative solution PinmemberMidnight15:00 7 Jan '04  
GeneralAn easier way PinmemberDiego Mijelshon1:50 8 Jan '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 7 Jan 2004
Article Copyright 2004 by Guy Baseke
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid