- 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
It's C#
Admin
I wonder what programming language is the code written in? I guess that's C ?
Admin
Dear God, I hope you're joking.
Admin
I wonder if you can read.
Admin
I've found that often, you can create Singletons that look like abstract factories from the caller's perspective. In most cases, it shouldn't matter to the caller whether the returned instance is unique or not. This allows you to stub out places where you expect more complicated implementations in the future as a Singleton. Other than that, I don't have a lot of use for Singletons.
Admin
How would you "fix" the constructor, to prevent the sub-class from being able to create as many instances of the parent as it wants, without disallowing all subclassing? I'm not trying to be a smart-aleck, that's a serious question. I haven't personally seen an implementation of Singleton that does this.
And for the person who asked if I graduated from Purdue, do you have a reason for insulting me (by referencing last week's WTF, for any actual Purdue graduates out there), or do you just make a habit of calling people names and leaving without justifying it?
Admin
That is completely false. Extending the features of a Singleton doesn't preclude a singleton somewhere in the object tree. As I said in a previous post, composition is usually ideal for Singletons but inheritance can certainly be used without compromising the integrity of implementation.
Uh, so what?
Admin
1) The singleton design pattern doesn't limit you to one instance. It allows control over the number of instances, and the typical usage is for a single instance, but the pattern doesn't preclude you from using it for more than that.
2) A static class isn't following the singleton design pattern. No instances are created. You have no object to pass around. That's an entirely different design pattern.
3) Subclassing does not break the "contract". There can still only be "one" instance of the singleton, even if a derived type exists and includes a public constructor and thus can be created multiple times.
4) A class with all static methods is not necessarily thread safe or stateless. In fact, this particular class is neither.
Admin
Make it private. The example for which someone posted a link had a "protected" no-arg constructor.
Admin
I agree. For a seldom used pattern, it sure gets a lot of publicity.
Admin
Just because a class has all static methods doesn't mean it's thread safe. Class members can hold state just as well as Object members. What is the difference between a single class member and a single Object member? Not much.
Seriously, read the pattern, specifically the purpose. If it's not sublclassed, it's not really a GoF singleton. Mos people who are implementing 'singletons' haven't actually read the pattern description.
Also, you can have sublcasses without making the constuctor protected (in Java at least) by making it package protected. Then you can have all the implementations be hidden and ensure one instance*.
*People get too hung up on the 'only one instance' thing. The fact of the matter is that in Java (and quite likely C#) it's almost impossible to enforce. Even if the contructor is private, you can still load class a second time in another classloader even in the same VM.
Admin
IIRC, if you make the constructor of the parent private, the sub-class cannot instantiate itself, because it cannot instantiate the parent.
I could be very wrong here, I suppose. It's been 2 years since I wrote any C++ code.
Admin
C++ being of course the language we're using here... wow...
Admin
Since I can't edit my post, I'll reply to my own to add a clarification:
I only entered this debate because Mung Kee pointed out that the sub-class was not prevented from making as many instances of the parent as it wanted. In retrospect, maybe wasn't complaining about that fact, though that's how I interpreted it at the time. I've never worried about this myself, to be honest. Any code can be misused, no matter how secure it is. There are limits to how far it is reasonable to go in the interest of preventing resourceful idiots from misusing your code.
Well, it's also been 2 years since I worked in Java. It's been 1 since I worked in C# (which is what this WTF was written in). And the features we're dealing with here (please, please notice I'm restricting the context of this statement) are generally similar enough between those 3 languages that for the most part, what you can do in one, you can do in the others. My experience with Singletons was in C++, so that was the one which was relevant. Apologies if I should have said "Singletons" instead of "C++ code".
Admin
You should be much more careful with your titles Alex, the Simpleton Pattern is not a Design Pattern, it's a Resign Pattern, the 5th Cremational Resign Pattern to be precise.
Here is the Resign Patterns document for those who don't know it. Please do read and try to understand it, it IS important.
Admin
Ah crap, forgot to close a link again :/
Admin
No, it's sweet. If I get tired of reading blue, not underlined text I can hover over it and it's red and underlined.
Admin
Which is nifty indeed when your corneas are tired from living :p
Admin
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.
It's a .Net lagnauge, and it's very cool.
Admin
'
>>> for x in range(70):
print S % (x, x)
0 [image]
1 [image]
2 [image]
3 [image]
4 [image]
5 [image]
6 [image]
7 [image]
8 [image]
9 [image]
10 [image]
11 [image]
12 [image]
13 [image]
14 [image]
15 [image]
16 [image]
17 [image]
18 [image]
19 [image]
20 [image]
21 [image]
22 [image]
23 [image]
24 [image]
25 [image]
26 [image]
27 [image]
28 [image]
29 [image]
30 [image]
31 [image]
32 [image]
33 [image]
34 [image]
35 [image]
36 [image]
37 [image]
38 [image]
39 [image]
40 [image]
41 [image]
42 [image]
43 [image]
44 [image]
45 [image]
46 [image]
47 [image]
48 [image]
49 [image]
50 [image]
51 [image]
52 [image]
53 [image]
54 [image]
55 [image]
56 [image]
57 [image]
58 [image]
59 [image]
60 [image]
61 [image]
62 [image]
63 [image]
64 [image]
65 [image]
66 [image]
67 [image]
68 [image]
69 [image]
[image] </font>
Admin
It does, just not explicitly. It's instanciated when the class is loaded, which is in most cases at exactly the time you first call the getInstance() method. Which makes the explicity lazy instantiation all the more idiotic.
Admin
I was waiting for someone to point this out. So what if you really really really need a true singleton? One thing you can do is just provide a stub which talks to a remote object. The neat thing about that pattern is that not only can you guaruntee true singleton behaviour, but the singleton can can exist across an entire application cluster.
Of course the performance penalty is not pretty...
I've never run into an instance when I needed a singleton that badly. Most cases where I think I might need a singleton, a factory works just fine.
Admin
Hmmmm...
Wouldn't that be more of a "Factory" design pattern than a singleton ? In that case, you use the singleton pattern to create a Factory for your interface implementation.
Basically, Singleton is a way to represent a unique resource.
--
Just my 2 euro-cents...
Admin
examples of the singleton pattern
// example one
public class LazyInit
{
private static LazyInit instance;
private static readonly object key = new object();
private LazyInit() {}
public static LazyInit Instance
{
get
{
lock(key) // ensure thread safety
{
if (instance == null)
instance = new LazyInit();
}
return instance;
}
}
}
// example two
public class EagerInit
{
// despite the lack of a static constructor
// when compiled, the compiler places the instantiation of the class
// inside the static constructor
private static readonly EagerInit instance = new LazyInit();
public static EagerInit Instance
{
get { return instance; }
}
}
// example three
public class EagerInit
{
private static readonly EagerInit;
// static constructor
static EagerInit()
{
/// do stuff
EagerInit = new EagerInit();
}
public static EagerInit Instance
{
get { return instance; }
}
}
Admin
Admin
AFAIK, the Singleton-mixin in Ruby does pretty much the same.
def MyClass
include singleton
end
Ruby might not be a .Net language, but it's very cool, too ;).
By the way, did anyone yet mention that our WTF today is not immune to cloning?
Admin
The language is c pound.
Admin
Thus you have a constructor for the children. Is implementing functionality not provided by a parent in new functions not the preferred way of doing this? Some brilliant new paradigm must have come along while I was napping.
I've never heard of an OO text claiming that a child must be able to instantiate its parent, or what would children of abstract classes do? Go mad, certainly.
Admin
Huh ?
And what about the MyBase.New(...) statement ? (sorry, VB here, could be MyParentClass::MyParentClass(...) in C++ if I'm not too rusty).
IIRC, making the constructor private prevents you from calling it from any derived class. It has to be protected for a derived class to access it. And calling the parent's constructor is usually advisable at some point. Or is it not ?
Admin
The intent states: Ensure a class only has one instance, and provide a global point of access to it.
It doesn't matter if the class is subclassed or not. The examples in the GoF book specifically provide a non-subclassed MazeFactory. It's still called a singleton. Subclassing the singleton instance is just a useful technique the authors mention, not the defining point of the pattern.
I find singletons to be extremely useful for (relatively) ubiquitous and unique resources. The most common use for me is the backend data store.
Admin
Why does this remind me so much of C, just much clumsier?
Admin
I wonder what programming language is the code written in? I guess that's COBOL?
Admin
What's wrong with static classes? I always use them as well, and I always declare them like thism, in case I need more than one:
private StatClass1
{
static string scName;
}
private StatClass2
{
static string scName;
}
Admin
Wrong. Double Checked locking doesn't work IN JAVA !!! It works perfectly well in C++.
Admin
Hahahahaha almost man........
Admin
There is also the matter of "process isolation". You can have only one instance of a singleton only when you are in the same process, but each process can have it's own instance. That is a problem when different apps with common libraries run in the same VM, and a future version of Java will target this specific problem so that all apps can run under one VM (a real memory hog when multiple instances are running, one for each app) with some kind of "virtual process isolation". I have no idea if and how .NET has solved this problem.
I understood the whole concept of process isolation much better myself when I introduced a fatal bug while trying to implement some kind of global constant in C++ code in a COM+ DLL and then realized that because it ran with "server" settings under one process (with the help of dllhost) it ended having one value across all clients :( :)
Oh, and one more thing: intra-process messaging mechanisms (names vary) included in OSs are there for the same reasons; applications are (and should be) isolated by the OS for safety and security reasons (their memory space, even if known, is untouchable by other processes/apps), but they should still be able to communicate somehow (a simple application-level solution is network-level communication).
Admin
Subclassing Singletons is most definitely not "the whole point". You may or may not want to subclass a Singleton, but IME you almost always do not. The GoF struggled to find an example of subclassed Singletons too.
Some languages do not support fully static classes (eg pre .NET versions of Delphi - an OO Pascal - only allowed static methods, not properties) so you cannot always use that instead of a Singleton. OTOH, Delphi did allow you to override static methods, so if you didn't need properties you could inherit from static classes instead of using Singletons.
Beware the language bias in the GoF :-)
Admin
It's more than likely than a CLI implementation of Ruby is being prepared (akin to IronPython).
I think there is already a Java Bytecode one.
Admin
The Singleton pattern is a nice source of abuse for people who don't know how to use it.
Admin
Not sure about C# but double locking strategy does not work in Java so I'll doubt it would work here. C# is a muppets language anyway.
Admin
Well, it works in theory, except that the JVMs are broken.
The problems exposed in that article probably won't apply to C# / CLR code.
Admin
LOL nice troll
Except all the java programmers I know are so hung up on design and pure theory that none of them have delivered a working product to the client, even after months and months of over-engineering.
At least this muppet gets the job done.
Admin
Of course calling the parent's constructor is usually more convenient and provides better encapsultation. That's the sort of thing that keeps us sane and would land us on daily wtf if we always did it some other way. But that doesn't mean everything must be done that way. It's quite plausible that constructors from otherwise similar derived classes could require wildly different initialization code, making a parent constructor rather useless if it's never instantiated.
(New Antipattern: Overriding base class functions by straight copying all code to child classes. Or one I've actually seen, making all methods of a base class protected and forcing all derived classes to consist of dozens of Child::GetX() { return Parent::GetX(); } etc.)
Admin
Nice re-troll. Hey, I know: this is a variation on the "deep-sea-dwelling elephants" - you don't know ANY Java programmers, right?
Not that over-engineering without any results isn't an existing problem, but it has nothing whatsoever to do with language and everything with software engineering processes.
Admin
Yeah Yeah, Whats your job, some gui monkey?
C# is crap, a) its a bad rip off b) it introduces all the rubbish that Java removed deliberately c) I think the the concept of if(this==null) in their own library code shows how well thought through it is. C# got to be the best WTF ever :).
Overengineered ? I notice how you muppets copy just about every thing in the open source java community. Got nothing better todo or any of your own ideas(bit like Microsoft)? What the hell was the point in writinhg Nant anyway??
I suggest you get a real job at a proper company and you will see that majority server side code is written in Java, and would never be written on C# for the obvious reasons i.e. stability, security , scalability, portability ......... Then again you probably wont beable given your writing that ****
Admin
Not sure where you see a problem. You can separate apps in regard to static class properties such as Singleton instances within the same VM by using a separate classloader for each app - or share the properties by using the same classloader, if that's what you want. This is nothing new, and all app servers do this to isolate apps from each other.
Google give no hits for "virtual process isolation"+java, but I think what you actually mean is already implemented in the current (1.5) version of Java. It's called "Class Data Sharing": http://java.sun.com/j2se/1.5.0/docs/guide/vm/class-data-sharing.html
Admin
OK, since these reasons are so obvious, please cite some specifics. How does C# (or .Net, rather) fail when it comes to stability, security and scalability? I will grant you that portability is a definite failing, but 1 outta 4 is not good odds.
Admin
Nope, it's the theory that's broken because it tries to out-smart the JIT compiler in the very sensitive area of multi-thread synchronization, and doesn't take into account out-of-order execution.
But the real joke is that the most simple and short implementation - initializing the Singleton in the static field declaration - has exactly the intended benefit (lazy initialization, no synchronization), without any drawbacks.
Admin
private static System.Net.IPEndPoint _Destination;
public static string Destination
{
get { return _Destination; }
set { _Destination = value; }
}
On top of everything else ....
should not compile!!! an IPEndPoint is not a string ... no implicit casts defined.
Admin
It's C-grass.