Macroware Technology

Welcome Portlet


Welcome to Macroware Technology Blog.

The purposes of this engineering blog:

- Share knowledge
- Learn
- Have fun
- Document what I was doing / thinking

Search Box

 

Private Area

Mailing List

Engineering Education

Engineering Organizations

Professional Career Networking Groups

Electronics Hobby

Trade Publications

Singleton Pattern

posted Wednesday, 14 October 2009
I learned about the concept of a singleton in object oriented methodology and I've started to understand the implementation in C#.  A singleton is a design pattern commonly used in object oriented programming in which a class is designed such that it can only be instantiated into a single object instead of the normal class that could be instantiated into multiple objects of the same class.  This is self enforced by the way the constructor function for the class is created.  Basically the class must contain a static variable (can be called inst) that points to an object of the class.  Then when the constructor is called (a function called Instance()), it checks to see if inst already has been assigned.  If it has it returns it, if it hasn't then it creates the object.  Anyone calling the constructor for the singleton class will get the reference to the single object of the class that exists and if it doesn't already exist it will be created.

Why would you want this?  It almost becomes a form of a global variable.  The object will always exist and be accessible to any other part of the software as long as they call the Instance() function to get the reference to the singleton object.  One place I saw it used is an object to store information read from a configuration file.  The first time the configuration data is needed in the software the configuration class constructor is called to create the singleton configuration object.  The configuration object only needs to be created once and anyone who needs config data from that point forward can easily get a reference to it by calling the constructor of the configuration class.

One question I had is that the singleton could end up existing after it has been created with no other part of the software having a reference to it.  I was told that garbage collection that occurs under the hood would destroy any objects who aren't referenced.  However, because of the way the singleton is implemented with the static variable inst in the class pointing to the object that is created, there will always be a reference to the object created.  The reference inst will be inside the same class that it is pointing to, but it is always there because it was declared static.  You can always directly access the instance from the watch window of your debugger no matter where you are in scope with:
classname.inst