SgDotNet
Singapore Professional .NET User Group -For Cool Developers

Singleton Pattern

rated by 0 users
This post has 21 Replies | 4 Followers

Top 10 Contributor
Posts 1,626
Firedancer Posted: 05-18-2005 2:04 PM

Hi Guys,

I'm confused recently over the implementation of the Singleton Pattern. In most of samples, the recommended implementation is:

public class MySingleton
{
private static MySingleton instance;
private Hashtable stuff;


public MySingleton()
{
stuff = new Hashtable();
}

    public static MySingleton CreateInstance
{
if(instance == null)
instance = new MySingleton();

return instance;
}


public Hashtable GetStuff()
{
return stuff;
}


}

The usage will be:

MySingleton c = MySingleton.CreateInstance();
Hashtable stuff = c.GetStuff();

However, is the following a singleton as well?

public class MyClass
{
private Hashtable stuff;


static MyClass
{
stuff = new Hashtable();
}

public static Hashtable GetStuff()
{
return stuff;
}

}

Usage is:

Hashtable stuff = MyClass.GetStuff();

What do you guys think? Confused [*-)]

Software development made easy with Paladin RAD Framework. Save some trees, use Stickies.NET
Top 10 Contributor
Posts 2,257
In my point of view a static instance != singleton instance. They are very similar and the differences are subtle.

A static instance is only one. A singleton pattern, despite its name, has scalable limit to the number of simultaneous objects running around. This is where pool management comes in; instantiate the necessary number and allocate accordingly to threads needing it (ala database Connection objects).

By nature of the above point, Static objects are referenced by their class names, so you cannot deal with multiple should your design call for it. True singleton objects are handled with variable references - you can many variables, of which are pointing to one or few same objects in reality.

A developer using a Static instance is aware (hopefully) of the singularity restriction, while a developer using classes with Singleton design need not necessarily be aware - that is the other class/library developer's job.

The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

Top 50 Contributor
Posts 146
A Singleton is usually only one instance.  And this control lies in the Singleton class itself like what Firedancer has given:

public static Configuration Current    {
      get
      {
             if (current == null)
             {
                     current = new Configuration();
             }

         return current;
        }
}

One usage that I've encounter is the Configuration class within an application.  There's a need to ensure consistency across all CRUD of the Configuration's data so that the application can act conherently within the context of the same application.   I've seen some DALC's implemented as Singleton as well.

IceLava, any example on "a pool" of Singleton that you are talking about?  Some reference has mentioned that briefly as well.
Knowledge, Hardwork, Patience...
Top 25 Contributor
Posts 485
This is my implementation of singleton in web application. But from what icelava mention, is this not singleton?

//inside class ajaxalinLogic
private const string LOGIC_INSTANCE = "Logic_instance";
public static ajaxalinLogic getInstance()
 {
            HttpContext CurrentCtxt = HttpContext.Current;
            object currentinst = CurrentCtxt.Application[LOGIC_INSTANCE];
            if( currentinst == null)
            {
                ajaxalinLogic n = new ajaxalinLogic();
                CurrentCtxt.Application[LOGIC_INSTANCE] = n;
            }
            return (ajaxalinLogic)CurrentCtxt.Application[LOGIC_INSTANCE] ;
  }
Yes, another version, another round of headaches. But that's progress.
Top 10 Contributor
Posts 2,257

Depending on how pedantic you want to get, I found a number who strictly insist Singleton is numerically singular, and you term it Object Pool pattern should you want to control the existence of a limited number of objects of a certain class.

An interesting question and discussion of a variant order:
http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=165813

And an interesting note of singleton vs static.

 Shunjie wrote:
ajaxalinLogic n = new ajaxalinLogic();

This is a singleton on basis you indeed instantiate a live instance, instead of using a static instance; only the method call is static, which is different.

The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

Top 25 Contributor
Posts 240

At first, everything pointed towards Singleton pattern being meaningless and not even deserving a name.

But I came across this definition, and I agree with it:

Singleton Pattern Definition
The Singleton pattern ensures that a class only has one instance and provides a global point of access to it from a well-known access point. The class implemented using this pattern is responsible for keeping track of its sole instance rather than relying on global variables to single instances of objects.
http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=486

Now the question is, why/when use it?

As far as I see, one case is when the creation of the instance is not possible with a static initializer. (eg. the instance of the object may get destroyed at some point, or the instantiation requires parameters that may not be available at that time)

So if the instance never gets destroyed and can be created at a fixed point such as application startup, I don't see any benifit in using the Singleton pattern over normal static methods, unless you anticipate switching to Singleton pattern in future without changing your code.

Top 25 Contributor
Posts 485
 hannes wrote:

Now the question is, why/when use it?



I use it if I want only a single instance of the class to manage the middle tier of the application and I do not want to give static modifier to the rest of the methods. 

Example, like keeping a collection of objects which is going to be the same to all user, so like what I did in my previous code, create a single instance of the class, and save it to a Application session.

Another implementation of it is most probably in developing socket server? Whereby 1 server will listen to many clients. Same case when we are using .net remoting also, can create a single instance of the class to listen to incoming request.


Yes, another version, another round of headaches. But that's progress.
Top 25 Contributor
Posts 232

Hane wrote

As far as I see, one case is when the creation of the instance is not possible with a static initializer. (eg. the instance of the object may get destroyed at some point, or the instantiation requires parameters that may not be available at that time)

I strongly believe Singleton is a very good and useful pattern despite whatever voice oppostion has. The only thing I'm not clear is how it get destroyed when there is no more client holding an instance to it remotely. Do we have to implement the logic to free it from memory or the GC handles it for us?

From what I know, .Net Remoting provides the InitialLifetimeServices to control the life time of the object. Com object use reference counting and ping all clients to see if they respond to the call to determine the lifetime of the object. COM+ recycle it's objects at a certain interval and recreate them when required.

Top 25 Contributor
Posts 240

Yep Shunjie I agree with your second example, but in the example where the object is created once, it is just a preference (a valid one) not to use static methods. Syntactically it is the Singleton Pattern, but none of its uses are utilised. This is what actually confused me, because I could not see why anyone would call it a pattern.

Yep the reference count to the objects is an important part of this pattern. Multiple clients may be holding different instances of the class, although all but one (or none) of them are on their way to being destroyed as soon as the references are released. I have no idea how this works with remoting etc. though.

You may not agree, but I see this method as equivalent to a class implementing the Singleton pattern. (Proper locking is not implemented, but simultaneous access would be harmless.)

  /// <summary>
  /// A cached list of measurements.
  /// The list will expire when modified from the web application.
  ///  (the list can be expired by using Cache.Remove("MeasureList");
  /// </summary>
  public epcdb.MeasureList MeasureList
  {
   get
   {
    epcdb.MeasureList lst = Cache["MeasureList"] as epcdb.MeasureList;
    if (lst == null)
    {
     lst = new epcdb.MeasureList();
     BusinessComponent BC = new BusinessComponent();
     BC.Populate(lst);
     Cache.Add("MeasureList",
      lst,
      null,
      System.Web.Caching.Cache.NoAbsoluteExpiration,
      System.Web.Caching.Cache.NoSlidingExpiration,
      System.Web.Caching.CacheItemPriority.High,
      null);
    }
    return lst;
   }
  }

Top 25 Contributor
Posts 485
 hannes wrote:

You may not agree, but I see this method as equivalent to a class implementing the Singleton pattern. (Proper locking is not implemented, but simultaneous access would be harmless.)

  ///
  /// A cached list of measurements.
  /// The list will expire when modified from the web application.
  ///  (the list can be expired by using Cache.Remove("MeasureList");
  ///
  public epcdb.MeasureList MeasureList
  {
   get
   {
    epcdb.MeasureList lst = Cache["MeasureList"] as epcdb.MeasureList;
    if (lst == null)
    {
     lst = new epcdb.MeasureList();
     BusinessComponent BC = new BusinessComponent();
     BC.Populate(lst);
     Cache.Add("MeasureList",
      lst,
      null,
      System.Web.Caching.Cache.NoAbsoluteExpiration,
      System.Web.Caching.Cache.NoSlidingExpiration,
      System.Web.Caching.CacheItemPriority.High,
      null);
    }
    return lst;
   }
  }



I do agree actually, because I practise that too. Smile [:)] I think basically the idea of to
1) check if the desired instance of null , if yes, instantiate it
2) place the instance on Cache / Application so that all the users share the same instance
3) Once the Cache expires, another instance will be created with the updated values
Yes, another version, another round of headaches. But that's progress.
Top 10 Contributor
Posts 2,257
 Shunjie wrote:
Example, like keeping a collection of objects which is going to be the same to all user, so like what I did in my previous code, create a single instance of the class, and save it to a Application session.

http://community.sgdotnet.org/forums/16226/ShowPost.aspx

The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

Top 50 Contributor
Posts 146
It's amazing how much discussion we can generate from the "simplest" Singleton, huh.

I remember someone mentioned that it's too simple to be even worth a thread, but look what depth we are going into. Geeked [8-|]
If not for this thread, I would have remained in the impression of a simple Singleton.

Let's see what more advanced DP can generate.Cool [H]
Knowledge, Hardwork, Patience...
Top 50 Contributor
Posts 146
 hannes wrote:

  ///
  /// A cached list of measurements.
  /// The list will expire when modified from the web application.
  ///  (the list can be expired by using Cache.Remove("MeasureList");
  ///
  public epcdb.MeasureList MeasureList
  {
   get
   {
    epcdb.MeasureList lst = Cache["MeasureList"] as epcdb.MeasureList;
    if (lst == null)
    {
     lst = new epcdb.MeasureList();
     BusinessComponent BC = new BusinessComponent();
     BC.Populate(lst);
     Cache.Add("MeasureList",
      lst,
      null,
      System.Web.Caching.Cache.NoAbsoluteExpiration,
      System.Web.Caching.Cache.NoSlidingExpiration,
      System.Web.Caching.CacheItemPriority.High,
      null);
    }
    return lst;
   }
  }



I think this is a good example of Singleton vs Static.  Cache cannot be static as the value is not known until runtime, yap?

Hannes, like to understand under what context is this "cache" being used.  What type of cache is being shared by every user?  My impression is that every user usually has a copy of their own cache (in context of web app, of course)

Side-note:
I think we have seen quite a couple of code samples; but knowing how to implement the DPs in code is only part of the puzzle.  There's seen to be lesser emphasis on the context of when/why the DP is used.  That's another important part of the puzzle.
Knowledge, Hardwork, Patience...
Top 10 Contributor
Posts 1,626

 Cyrus Crypt wrote:
It's amazing how much discussion we can generate from the "simplest" Singleton, huh.

I remember someone mentioned that it's too simple to be even worth a thread, but look what depth we are going into. Geeked [8-|]
If not for this thread, I would have remained in the impression of a simple Singleton.

Let's see what more advanced DP can generate.Cool [H]

Ok Cyrus Cryptie... I admit I was being a Simpleton earlier on the subject Embarrassed [:$] but I did some justice to it by starting this thread. Stick out tongue [:P] So you can stop rubbing it in Crying [:'(]

Anyway, I'm happy to see so many Paladin code being thrown across the forums nowadays. Really gives me that warm-fuzzy-feelin.

As for all the debates, I still don't know whether which of the methods I posted earlier is correct. Confused [*-)]

Software development made easy with Paladin RAD Framework. Save some trees, use Stickies.NET
Top 10 Contributor
Posts 2,257
 Firedancer wrote:
As for all the debates, I still don't know whether which of the methods I posted earlier is correct.
Perhaps a point that was hinted but never explicitly highlighted: do you want whatever that object contains to remain throughout from start to end of application life? Static instances die with the application's end, a singleton can be destroyed as and when you need to.

The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

Page 1 of 2 (22 items) 1 2 Next > | RSS
Copyright SgDotNet 2004-2008
Powered by Community Server (Commercial Edition), by Telligent Systems