• (cs)

    You get an A for trying, but an F for failing to understand when & why you impliment this!

  • (cs)

    <FONT face=Georgia>My previous post is [image] approved</FONT>

  • (cs)

    Yeah. I am the first person to post. I always want to be number one.

  • anonymous (unregistered)

    Today we salute you Mr. Misuser of the Singleton Design Pattern...

  • anonymous (unregistered) in reply to anonymous

    actually, it's Mr. Non-user of the Singleton Design Pattern

  • (cs) in reply to haveworld
    haveworld:
    Yeah. I am the first person to post. I always want to be number one.


    3rd is not that bad either.
  • skjaero (unregistered)

    If I ever had to have an occasion to say WTF, then this must be it!

    WTF!!


  • Paul Tomblin (unregistered)

    What language is this?  It looks almost like Java, but these get/set things are confusing me.

  • (cs) in reply to Paul Tomblin

    This is C# and those are properties.

     

  • blapato (unregistered)

    So what kind of application is he writing that he would only ever need one instance of a notification message?  That must be one all encompassing message .

  • (cs)

    The biggest WTF here is the Singleton pattern itself, the fact that it's the first one he thought of as useful and that it even took time to come up with that answer.

    I mean, design patterns are touted as the pinnacle of modern OO programming, yet 95% of the people you ask about them, the first and only one they can cite is Singleton, which is.... basically an OO way of creating a global variable! Helloooo? Weren't global variables supposed to be a horrible abomination from back in the middle ages before structured programming was invented?

  • (cs) in reply to blapato

    I'm still not clear how it 'didn't work'.  The way most people use 'Singletons' is almost completely indistinct from the way you would use a class with just static methods.

  • (cs) in reply to brazzy

    brazzy:

    I mean, design patterns are touted as the pinnacle of modern OO programming, yet 95% of the people you ask about them, the first and only one they can cite is Singleton, which is.... basically an OO way of creating a global variable! Helloooo? Weren't global variables supposed to be a horrible abomination from back in the middle ages before structured programming was invented?

    This is a result of a fundamental misunderstanding of the Singleton pattern more than the pattern itself.  It's the most overused and misused design pattern.

  • (cs)

    For those that don't know, the Singleton Pattern basically states that all classes should follow the same single pattern.  That pattern?  The Singleton Pattern, of course.

  • NewbieCoder (unregistered) in reply to dubwai
    dubwai:
    I'm still not clear how it 'didn't work'.  The way most people use 'Singletons' is almost completely indistinct from the way you would use a class with just static methods.


    If I had to guess (and I do) it's because the constructor is marked private and there is no public way to create a new instance of that class.
  • (cs)

    Re-read TFA.  The guy used static classes EVERYWHERE in his project.

    That's a major WTF!

  • Dummy (unregistered)

    What kills me is the example at http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1

    <font color="blue">class</font> Singleton

      {

        <font color="blue">private</font> <font color="blue">static</font> Singleton instance;


        <font color="green">// Note: Constructor is 'protected'</font>

        <font color="blue">protected</font> Singleton()

        {

        }


        <font color="blue">public</font> <font color="blue">static</font> Singleton Instance()

        {

          <font color="green">// Use 'Lazy initialization' </font>

          <font color="blue">if</font> (instance == <font color="blue">null</font>)

          {

            instance = <font color="blue">new</font> Singleton();

          }


          <font color="blue">return</font> instance;

        }

      }

    }

    That looks like a great way to get more than one instance if you happen to run a multi-threaded app...

  • John (unregistered)

    I love this forum! So many great coding snippets that I use for my projects.

  • (cs) in reply to Dummy
    Anonymous:
    What kills me is the example at http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1

    <font color="blue">class</font> Singleton

      {

        <font color="blue">private</font> <font color="blue">static</font> Singleton instance;


        <font color="green">// Note: Constructor is 'protected'</font>

        <font color="blue">protected</font> Singleton()

        {

        }


        <font color="blue">public</font> <font color="blue">static</font> Singleton Instance()

        {

          <font color="green">// Use 'Lazy initialization' </font>

          <font color="blue">if</font> (instance == <font color="blue">null</font>)

          {

            instance = <font color="blue">new</font> Singleton();

          }


          <font color="blue">return</font> instance;

        }

      }

    }

    That looks like a great way to get more than one instance if you happen to run a multi-threaded app...

    Except the example you misquoted has a thread lock around the creation of the instance. This is assuming of course that I am reading the C# code correctly.

  • (cs)

    Damn right it doesn't work when he doesn't provide a public method that invokes the private constructor.  He should have something like:

    private static NotificationMessage _message = null;

    public static NotificationMessage getInstance(){
        if(_message == null){
           _message = new NotificationMessage();
        }
        return _message;
    }

    The previous poster was right too.  I can see having a singleton Messenger but a singleton NotificationMessage is just plain jackass.

    Not to rip on C# but those accessors and mutators are a little kooky for me.  Can one also use longhand if one likes ( e.g. getMessageType() and setMessageType() )?  It's a little ironic that I would be asking since I hate typing out these methods.

  • Hans Hammer (unregistered) in reply to Zorlen

    Check out these Singleton thread-safety issues http://www.yoda.arachsys.com/csharp/singleton.html

  • (cs) in reply to Dummy
    Anonymous:
    What kills me is the example at http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1

    <font color="blue">class</font> Singleton

      {

        <font color="blue">private</font> <font color="blue">static</font> Singleton instance;


        <font color="green">// Note: Constructor is 'protected'</font>

        <font color="blue">protected</font> Singleton()

        {

        }


        <font color="blue">public</font> <font color="blue">static</font> Singleton Instance()

        {

          <font color="green">// Use 'Lazy initialization' </font>

          <font color="blue">if</font> (instance == <font color="blue">null</font>)

          {

            instance = <font color="blue">new</font> Singleton();

          }


          <font color="blue">return</font> instance;

        }

      }

    }

    That looks like a great way to get more than one instance if you happen to run a multi-threaded app...



    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

  • Dummy (unregistered) in reply to Zorlen

    Except the example you misquoted has a thread lock around the creation of the instance. This is assuming of course that I am reading the C# code correctly.

    There's no thread lock there. It's checking to see merely that the instance is null. Two threads can perform this same check simultaneously, and construct the two instances at the same time. How did I misquote that?

    Finally, they do provide a second example using double-checked locking to provide a lazy synchronized init, but double-checked locking doesn't work:

    http://www-128.ibm.com/developerworks/java/library/j-dcl.html

  • Dummy (unregistered) in reply to Mung Kee

    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

    I'm not sure you understand. If two threads call Instance() at the same time, you could get two instances created. Both threads check that instance is null at the same time (before either constructs it and sets that field).

  • (cs) in reply to Mung Kee
    Mung Kee Flinging Poo:
    Not to rip on C# but those accessors and mutators are a little kooky for me.  Can one also use longhand if one likes ( e.g. getMessageType() and setMessageType() )?  It's a little ironic that I would be asking since I hate typing out these methods.


    Yeah, you can still type out the accessor/mutator methods just like Java.  It's just creating methods instead of using the built-in syntactic sugar of .NET properties.  In reality, this:

    public int IntProperty
    {
        get { return _IntMember; }
        set { _IntMember = value; }
    }

    gets compiled into the IL as something like this:

    public int get_IntProperty()
    {
        return _IntMember;
    }

    public void set_IntProperty(int value)
    {
        _IntMember = value;
    }
  • (cs) in reply to Dummy
    Anonymous:
    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

    I'm not sure you understand. If two threads call Instance() at the same time, you could get two instances created. Both threads check that instance is null at the same time (before either constructs it and sets that field).


    I think the main thing is that it isn't going to necessarily be used in a multi-threaded application.  Of course, it wouldn't hurt to throw a lock into the Instance method, but it isn't necessary in a single threaded app.  In that referenced article, you can see a more thread-safe example immediately following the non-thread safe one.
  • (cs) in reply to Dummy

    there are two ways I will use singletons,

    They are private static objects that reside within another object. The owning object does not allow any kind of direct access to the static, and the static is initalised and it's data filled in a static constructor (ie, first time the class is used) - from then on it cannot change. A static cache is a good example (say, a set of image codecs or something).

    The singleton is accessed through a generic class Singleton<classType>.Instance ..., initalised in a wrapper class that also uses a static member with a static constructor. Using the Singleton<>.Instance member will return an object that is a singleton to the application instance running. Pretty much using a thread check. So two instances of the same application will not share singletons, and non-application instance created threads will not be able to access it either.

    Seems to work well for me.

  • (cs) in reply to Mung Kee

    Regarding the subclassing issue raised by "Mung Kee":

    This is why, in Java or C#, you should use final or sealed to make sure that the Singleton class is not used as a base class.


    Regarding the threading issue raised by "Dummy":

    If you know your Singleton will be used in multi-threaded apps, then you should use a mutex mechanism to protect critical actions occurring within that class, such as the allocation, deallocation, reference counting, property changes, etc.


    It is also possible to create a per-thread Singleton which allows one and only one instance per thread, without interference between these instances.


    The biggest problem (really it's an annoyance) I have with Singleton is that, AFAIK no language really has any mechanism by which it is possible to solve both of the above problems while preserving the ability to use a Singleton "mix-in" base class or interface.  Which means that the functionality has to be re-written for each class that needs to be a Singleton.  Though in C++ this annoyance could probably be alleviated using macros.


    If anyone knows of any way to solve all three of these problems in fell swoop, please post!

  • (cs) in reply to Dummy

    The simple implementation gives you one shared instance, but doesn't guarantee that only one instance is ever created.

    The difference can become very important if the "singleton" aquries state or system resources.

    The more precise implementations get squirely as one fights between safety and lazyness

    http://www.yoda.arachsys.com/csharp/singleton.html Nice Nested Lazy version.

     http://msdn.microsoft.com/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp?frame=true 

    Round up : http://weblogs.asp.net/mnolton/archive/2004/02/02/66237.aspx

     

    Of course the WTF is not about a failure due to a non-stringent implementation of the Singleton, its a static class.

     

  • sparky (unregistered) in reply to haveworld

    Try second PERSON

  • (cs) in reply to Dummy
    Anonymous:
    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

    I'm not sure you understand. If two threads call Instance() at the same time, you could get two instances created. Both threads check that instance is null at the same time (before either constructs it and sets that field).


    Oh, I understand completely.  All I said was, why do I have to call Instance() at all when the constructor allows protected access.  If I just use the constructor when does instance == null get evaluated?  It doesn't. 

    Does "protected" in C# mean 'subclass access' as it does in Java?
  • (cs) in reply to Ytram

    Hello all, long time listener and first time caller....

    It should be noted this only works in .NET 2.0 when using C#.  I am sure other languages would have allowed it earlier though, since not all languages support properties.

  • (cs) in reply to kleinux
    kleinux:
    Hello all, long time listener and first time caller....

    It should be noted this only works in .NET 2.0 when using C#.  I am sure other languages would have allowed it earlier though, since not all languages support properties.


    Being a noob, this was supposed to respond to Ytram's description on properties.
  • (cs) in reply to Mung Kee

    Mung Kee See:
    Does "protected" in C# mean 'subclass access' as it does in Java?


    Yeah.

  • Ivy League (unregistered) in reply to WaterBreath

    WaterBreath... did you graduate from Purdue?

  • (cs) in reply to kleinux
    kleinux:
    kleinux:
    Hello all, long time listener and first time caller....

    It should be noted this only works in .NET 2.0 when using C#.  I am sure other languages would have allowed it earlier though, since not all languages support properties.


    Being a noob, this was supposed to respond to Ytram's description on properties.


    We were talking specifically about properties in C#, and it's not specific to .NET 2.0, it's been in since 1.1 at least, and I'm pretty sure it was in 1.0.
  • sparky (unregistered) in reply to haveworld
    haveworld:
    haveworld:
    Yeah. I am the first person to post. I always want to be number one.


    3rd is not that bad either.

    or Second PERSON

  • (cs) in reply to Ytram
    Ytram:
    kleinux:
    kleinux:
    Hello all, long time listener and first time caller....

    It should be noted this only works in .NET 2.0 when using C#.  I am sure other languages would have allowed it earlier though, since not all languages support properties.


    Being a noob, this was supposed to respond to Ytram's description on properties.


    We were talking specifically about properties in C#, and it's not specific to .NET 2.0, it's been in since 1.1 at least, and I'm pretty sure it was in 1.0.


    They were there in 1.1 (and probably in 1.0), but you would get a compilation error in C# if you tried to access them.  Perhaps there is a compiler setting that can override this, but I have not seen it. 
  • (cs) in reply to WaterBreath
    WaterBreath:
    Regarding the subclassing issue raised by "Mung Kee":

    This is why, in Java or C#, you should use final or sealed to make sure that the Singleton class is not used as a base class.



    Hey, great idea!  Let's throw inheritance out the window because you don't want to fix the WTF-ed constructor.  Although Composition is usually more suitable, there is still a place for inheritance when developing Singletons.

  • (cs) in reply to kleinux
    kleinux:


    They were there in 1.1 (and probably in 1.0), but you would get a compilation error in C# if you tried to access them.  Perhaps there is a compiler setting that can override this, but I have not seen it. 


    To clarify, the error would occur in accessing the get_Method() or set_Method(object o) and not Method = foo
  • (cs) in reply to kleinux
    kleinux tissues:
    They were there in 1.1 (and probably in 1.0), but you would get a compilation error in C# if you tried to access them.  Perhaps there is a compiler setting that can override this, but I have not seen it.


    Are you saying that you would get a compilation error when trying to access a property of an object in .NET 1.1?   That must have been a pain when you're trying to access the Length of a string or the Count of a collection.

    Perhaps we are talking about different things, but properties most certainly work in .NET 1.1.
  • (cs) in reply to Dummy

    This is the first time I have posted on WTF so first off, hi everyone. 

    Any who, I thought the purpose of the singleton pattern was to return a common reference to the same object in memory.  So yeah, it would be alot like a global variable/object. 

  • (cs) in reply to kleinux
    kleinux:
    kleinux:


    They were there in 1.1 (and probably in 1.0), but you would get a compilation error in C# if you tried to access them.  Perhaps there is a compiler setting that can override this, but I have not seen it. 


    To clarify, the error would occur in accessing the get_Method() or set_Method(object o) and not Method = foo


    Ahh, okay, I wasn't referring to how to use them, I was just explaining what they actually get compiled into.  You will get an error if you try to explicitly call get_PropertyName().  You will also get an error if you have a property set up and you attempt to define a method named get_PropertyName().
  • (cs)

    Just so you all know it's very easy to create a thread-safe singleton (at least in Java).  Although this does not use lazy instantiation.

  • (cs) in reply to Steve

    Arrg...

    public class Singleton{
        public static final Singleton instance = new Singleton();

        private Singleton(){}

        ...

    }

  • (cs) in reply to Steve

    Most everyone on this thread should take a minute and read the GoF Singleton pattern.  The whole point is for the Singleton to be subclasses so that you can provide different implementations at runtime.  If you are just creating a single instance with some methods where there is no polyporphism, then there's very little difference between that and a 'static class' (a class will all static methods.)

  • (cs) in reply to dubwai

    dubwai:
    where there is no polyporphism

    I mean, 'polymorphism'.  Polyporphism is something different altogether.

  • (cs)

    I always thought Observer was the design pattern everyone learns first, often without realising it.

  • (cs) in reply to dubwai
    dubwai:
    Most everyone on this thread should take a minute and read the GoF Singleton pattern.  The whole point is for the Singleton to be subclasses so that you can provide different implementations at runtime.  If you are just creating a single instance with some methods where there is no polyporphism, then there's very little difference between that and a 'static class' (a class will all static methods.)


    Well said, dubwai.  The purpose and proper implementation of the pattern is often misunderstood, as seen in the example.  I have met a few who believe that, because there is a single instance in memory, for some reason there are different rules that apply to it, when inheritance and polymorphism are certainly not out of the question.  So long as the minimum set of requirements for the pattern are satisfied, there is no reason why you can't subclass it.
  • (cs) in reply to dubwai
    dubwai:
    Most everyone on this thread should take a minute and read the GoF Singleton pattern.  The whole point is for the Singleton to be subclasses so that you can provide different implementations at runtime.  If you are just creating a single instance with some methods where there is no polyporphism, then there's very little difference between that and a 'static class' (a class will all static methods.)


    While you could (in most cases) use a class with all static methods the same as a Singleton, a class with all static methods should be thread safe and stateless where a Singleton may not be.  Of course you could write the code anyway you want.

    Allowing subclassing of a Singleton destroys the contract that 'there can be only one'.  Sounds to me like you're getting confused with the Factory pattern maybe?

    Singletons are often used as entrypoints into resources.

Leave a comment on “The Simpleton Design Pattern”

Log In or post as a guest

Replying to comment #48225:

« Return to Article