Comment On The Simpleton Design Pattern

Andrew Smith was attending a presentation on design patterns and ran into a fellow programmer he knew from college. While they were chatting, the colleague asked Andrew a rather curious question: "what pattern do you think is most useful?" Andrew thought about it for a little bit, and said that he had found the Singleton pattern very helpful on some recent projects. [expand full text]
« PrevPage 1 | Page 2 | Page 3 | Page 4Next »

Re: The Simpleton Design Pattern

2005-10-26 13:56 • by travisowens
You get an A for trying, but an F for failing to understand when & why you impliment this!

Re: The Simpleton Design Pattern

2005-10-26 13:57 • by travisowens

My previous post is  approved

Re: The Simpleton Design Pattern

2005-10-26 13:59 • by haveworld
Yeah. I am the first person to post. I always want to be number one.

Re: The Simpleton Design Pattern

2005-10-26 13:59 • by anonymous
Today we salute you Mr. Misuser of the Singleton Design Pattern...

Re: The Simpleton Design Pattern

2005-10-26 14:00 • by anonymous
48180 in reply to 48179
actually, it's Mr. Non-user of the Singleton Design Pattern

Re: The Simpleton Design Pattern

2005-10-26 14:01 • by haveworld
48181 in reply to 48178
haveworld:
Yeah. I am the first person to post. I always want to be number one.


3rd is not that bad either.

Re: The Simpleton Design Pattern

2005-10-26 14:01 • by skjaero


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



WTF!!





Re: The Simpleton Design Pattern

2005-10-26 14:11 • by Paul Tomblin
What language is this?  It looks almost like Java, but these get/set things are confusing me.

Re: The Simpleton Design Pattern

2005-10-26 14:12 • by rhino-x
48186 in reply to 48185

This is C# and those are properties.


 

Re: The Simpleton Design Pattern

2005-10-26 14:25 • by blapato
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 .

Re: The Simpleton Design Pattern

2005-10-26 14:35 • by brazzy
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?

Re: The Simpleton Design Pattern

2005-10-26 14:35 • by dubwai
48190 in reply to 48187
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.

Re: The Simpleton Design Pattern

2005-10-26 14:39 • by dubwai
48191 in reply to 48189

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.

Re: The Simpleton Design Pattern

2005-10-26 14:41 • by Beek
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.

Re: The Simpleton Design Pattern

2005-10-26 14:42 • by NewbieCoder
48193 in reply to 48190
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.

Re: The Simpleton Design Pattern

2005-10-26 14:49 • by christoofar
Re-read TFA.  The guy used static classes **EVERYWHERE** in his project.



That's a major WTF!

Re: The Simpleton Design Pattern

2005-10-26 14:50 • by Dummy
What kills me is the example at http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1



class Singleton


  {


    private static Singleton instance;





    // Note: Constructor is 'protected'




    protected Singleton()


    {


    }





    public static Singleton Instance()


    {


      // Use 'Lazy initialization'




      if (instance == null)


      {


        instance = new Singleton();


      }





      return instance;


    }


  }


}



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

Re: The Simpleton Design Pattern

2005-10-26 14:56 • by John
I love this forum! So many great coding snippets that I use for my projects.

Re: The Simpleton Design Pattern

2005-10-26 14:57 • by Zorlen
48198 in reply to 48196
Anonymous:
What kills me is the example at http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1



class Singleton


  {


    private static Singleton instance;





    // Note: Constructor is 'protected'




    protected Singleton()


    {


    }





    public static Singleton Instance()


    {


      // Use 'Lazy initialization'




      if (instance == null)


      {


        instance = new Singleton();


      }





      return 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.

Re: The Simpleton Design Pattern

2005-10-26 15:00 • by Mung Kee
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.

Re: The Simpleton Design Pattern

2005-10-26 15:04 • by Hans Hammer
48200 in reply to 48198
Check out these Singleton thread-safety issues http://www.yoda.arachsys.com/csharp/singleton.html

Re: The Simpleton Design Pattern

2005-10-26 15:04 • by Mung Kee
48201 in reply to 48196
Anonymous:
What kills me is the example at http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1



class Singleton


  {


    private static Singleton instance;





    // Note: Constructor is 'protected'




    protected Singleton()


    {


    }





    public static Singleton Instance()


    {


      // Use 'Lazy initialization'




      if (instance == null)


      {


        instance = new Singleton();


      }





      return 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.

Re: The Simpleton Design Pattern

2005-10-26 15:05 • by Dummy
48202 in reply to 48198
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


Re: The Simpleton Design Pattern

2005-10-26 15:09 • by Dummy
48203 in reply to 48201

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).

Re: The Simpleton Design Pattern

2005-10-26 15:13 • by Ytram
48204 in reply to 48199
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;

}

Re: The Simpleton Design Pattern

2005-10-26 15:18 • by Ytram
48206 in reply to 48203
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.

Re: The Simpleton Design Pattern

2005-10-26 15:25 • by Graham
48208 in reply to 48203
there are two ways I will use singletons,

1.
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).

2.
The singleton is accessed through a generic class Singleton.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.

Re: The Simpleton Design Pattern

2005-10-26 15:28 • by WaterBreath
48209 in reply to 48201
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!

Re: The Simpleton Design Pattern

2005-10-26 15:31 • by Free
48210 in reply to 48196

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.


 

Re: The Simpleton Design Pattern

2005-10-26 15:36 • by sparky
48211 in reply to 48181
Try second PERSON

Re: The Simpleton Design Pattern

2005-10-26 15:37 • by Mung Kee
48212 in reply to 48203
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?

Re: The Simpleton Design Pattern

2005-10-26 15:37 • by kleinux
48213 in reply to 48204
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.

Re: The Simpleton Design Pattern

2005-10-26 15:41 • by kleinux
48214 in reply to 48213
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.

Re: The Simpleton Design Pattern

2005-10-26 15:41 • by Ytram
48215 in reply to 48212
Mung Kee See:
Does "protected" in C# mean 'subclass access' as it does in Java?




Yeah.

Re: The Simpleton Design Pattern

2005-10-26 15:41 • by Ivy League
48216 in reply to 48209
WaterBreath... did you graduate from Purdue?

Re: The Simpleton Design Pattern

2005-10-26 15:42 • by Ytram
48217 in reply to 48214
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.

Re: The Simpleton Design Pattern

2005-10-26 15:44 • by sparky
48218 in reply to 48181
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

Re: The Simpleton Design Pattern

2005-10-26 15:54 • by kleinux
48219 in reply to 48217
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. 

Re: The Simpleton Design Pattern

2005-10-26 15:56 • by Mung Kee
48220 in reply to 48209
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.

Re: The Simpleton Design Pattern

2005-10-26 16:03 • by kleinux
48221 in reply to 48219
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

Re: The Simpleton Design Pattern

2005-10-26 16:04 • by Ytram
48222 in reply to 48219
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.

Re: The Simpleton Design Pattern

2005-10-26 16:07 • by tdog
48223 in reply to 48196

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. 

Re: The Simpleton Design Pattern

2005-10-26 16:08 • by Ytram
48224 in reply to 48221
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().

Re: The Simpleton Design Pattern

2005-10-26 16:17 • by Steve
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.

Re: The Simpleton Design Pattern

2005-10-26 16:19 • by Steve
48226 in reply to 48225
Arrg...



public class Singleton{

    public static final Singleton instance = new Singleton();



    private Singleton(){}



    ...



}

Re: The Simpleton Design Pattern

2005-10-26 16:38 • by dubwai
48227 in reply to 48226
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.)

Re: The Simpleton Design Pattern

2005-10-26 16:49 • by dubwai
48228 in reply to 48227

dubwai:
where there is no polyporphism


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

Re: The Simpleton Design Pattern

2005-10-26 16:58 • by technites
I always thought Observer was the design pattern everyone learns first, often without realising it.

Re: The Simpleton Design Pattern

2005-10-26 17:05 • by Mung Kee
48232 in reply to 48227
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.

Re: The Simpleton Design Pattern

2005-10-26 17:09 • by Steve
48233 in reply to 48227
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.

« PrevPage 1 | Page 2 | Page 3 | Page 4Next »

Add Comment