- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
You get an A for trying, but an F for failing to understand when & why you impliment this!
Admin
<FONT face=Georgia>My previous post is [image] approved</FONT>
Admin
Yeah. I am the first person to post. I always want to be number one.
Admin
Today we salute you Mr. Misuser of the Singleton Design Pattern...
Admin
actually, it's Mr. Non-user of the Singleton Design Pattern
Admin
3rd is not that bad either.
Admin
If I ever had to have an occasion to say WTF, then this must be it!
WTF!!
Admin
What language is this? It looks almost like Java, but these get/set things are confusing me.
Admin
This is C# and those are properties.
Admin
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 .
Admin
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?
Admin
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.
Admin
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.
Admin
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.
Admin
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.
Admin
Re-read TFA. The guy used static classes EVERYWHERE in his project.
That's a major WTF!
Admin
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...
Admin
I love this forum! So many great coding snippets that I use for my projects.
Admin
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.
Admin
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.
Admin
Check out these Singleton thread-safety issues http://www.yoda.arachsys.com/csharp/singleton.html
Admin
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.
Admin
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
Admin
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).
Admin
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;
}
Admin
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.
Admin
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.
Admin
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!
Admin
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.
Admin
Try second PERSON
Admin
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?
Admin
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.
Admin
Being a noob, this was supposed to respond to Ytram's description on properties.
Admin
Yeah.
Admin
WaterBreath... did you graduate from Purdue?
Admin
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.
Admin
or Second PERSON
Admin
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.
Admin
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.
Admin
To clarify, the error would occur in accessing the get_Method() or set_Method(object o) and not Method = foo
Admin
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.
Admin
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.
Admin
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().
Admin
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.
Admin
Arrg...
public class Singleton{
public static final Singleton instance = new Singleton();
private Singleton(){}
...
}
Admin
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.)
Admin
I mean, 'polymorphism'. Polyporphism is something different altogether.
Admin
I always thought Observer was the design pattern everyone learns first, often without realising it.
Admin
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.
Admin
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.