Jump to content
  • Advertisement
Sign in to follow this  
Pxtl

Am I crazy? what is a singleton?

This topic is 5093 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been looking into design patterns, particularly after experimenting with Python and Ruby and the bizarre lexical constructs you can do in them. The thing I notice reading is this: I can't figure out what a Singleton does. I mean, everyone says the same thing: if you only need one copy of the object, then this is how you do it. But the exact nature of this is strange: sometimes people show it as a shared object - that is, you have one object shared between all objects, and you use the class to access it. In that case, isn't this the same as a class full of static members, effectively a big global? Some people end up just using it as shorthand - functionally its the same as a regular static object, except using the constructor instead of an "initialize" function and a destructor instead of a "finalize" function. For example, launching a core system like the graphics library could be done like this. Add in refcounting and you've got a good system for a single shared service. But as I've seen it, that's not a really popular approach, so I remain confused. The final approach is access control - you need only one system at a time to access the mouse, so you say that they have to "construct" the mouse, and other objects cannot do that while it is in existance. Essentially this makes the singleton a hybrid of the "protected" types common in multithreading and a memory-saving and quick-wiping scheme that throws the data out while not in use. So which of these is the actual purpose of the Singleton? [Edited by - Magmai Kai Holmlor on July 6, 2004 11:07:29 PM]

Share this post


Link to post
Share on other sites
Advertisement
A singleton is defined by the GoF as "Ensure a class only has one instance, and provide a global point of access to it".

Anything else is just implementation details, there are 101 ways to implement it.

Share this post


Link to post
Share on other sites
Okay, some of the documents I read didn't mention a global point of access to it. That nixes the Singleton as a protection scheme for mutual exclusion. In that case, it is really just a global static class with a constructor and a destructor isnt it?

I mean, couldn't it be replaced with a functional module that has a "initialize" and "finalize" function?

Share this post


Link to post
Share on other sites

"A singleton is a global object for which only one instance exists in the whole application. Most applications, and definitely all games, need global objects that must be visible from many different classes and scopes. A texture manager, the joystick controller object, and even the player class are all singletons. We need to have them visible at all times, and we only want to store one of these in memory. "

Core Techniques and Algorithms in Game Programming
By Daniel Sánchez-Crespo Dalmau


but wait, there's more

Thus, the solution to the singleton problem is different from those explained earlier. It starts by declaring a class that has only one public method, which will be used to request an instance of the singleton. All instances actually point at the same structure, so this request call must create the singleton for the first call and just return pointers to it in subsequent calls. Thus, the constructor is a protected member, and all outside accesses to the class are done by the instance request call.

Here is the code for a sample singleton:


class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance () {
if (_instance == 0)
{
instance = new Singleton;
}
return _instance;
}


Any class requiring access to the singleton will just create one singleton variable (which will be different in each case).But all these variables will end up pointing at the same, unique object in memory.

Share this post


Link to post
Share on other sites
How is this a "pattern" - isn't it just global? And yet so much I find describes the Singleton as "don't use evil globals". It seems to be just a really elaborate way of writing a global but pretending its an object to me.

Share this post


Link to post
Share on other sites
Singletons are not replacements for globals. The only thing they have in common is the global point of access. The singleton pattern ensures that there is only one instance of a class, a global does not do this.

Share this post


Link to post
Share on other sites
Quote:

Singletons are not replacements for globals. The only thing they have in common is the global point of access.

No, but people still use them as a replacement for globals. Singletons are way overused; infact, in my entire 2 years I've been programming I've never seen a situation where a singleton had to be used instead of just passing around the instance of the class.

Share this post


Link to post
Share on other sites
A singleton never has to be used, but when you have a class for which only one instance can logically exist it is vastly simpler to use a singleton than to pass it around the block to everything.

Of course this technique can be abused just like any other, its merely a matter of making good design decisions.

Share this post


Link to post
Share on other sites
Quote:
Original post by Jingo
Singletons are not replacements for globals. The only thing they have in common is the global point of access. The singleton pattern ensures that there is only one instance of a class, a global does not do this.


I could be completely misunderstanding, but when I fill in the missing words and substitute the backreferences in "a global does not do this", I get "using a global variable does not ensure that there is only one instance of the global variable."

Uhh...

The only reasons I can think of why any 'pattern' would ever be needed are:

- to solve static order of initialization problems. (Which, in Java at least, are a Can't Happen(TM), unless you have a cyclic dependency that would need some other resolution strategy *anyway*. C++ certainly allows the possibility though.)

- to allow runtime polymorphism in order to select some singleton subclass to treat as "the instance" (I am told this gets used for abstracting away rendering layers when you - somehow! - don't know until runtime which graphics API you're going to use.)

But this seems bug-prone (suppose you switch during execution for some reason - admittedly not likely with the graphics API example - and other classes have cached references to the old singleton?), and the same effect can be had with static classes just as easily - just add appropriate extra state, and consult it when deciding what action to take. If necessary, use it to dispatch to other static classes.

Of course, this starts to smell in Java (since you're implementing your own dispatch mechanism, and don't get the luxury of pointer lookup of the classes - unless you use reflection - so that you're stuck with else-if's) but it seems like it would be quite idiomatic in Python, say (where classes and functions are already objects) or heck, in C++ (where your static class could manage itself rather nicely by swapping function pointers around).

Edit:

Quote:
Original post by Illumini
A singleton never has to be used, but when you have a class for which only one instance can logically exist it is vastly simpler to use a singleton than to pass it around the block to everything.


Why pass it around if you can get away with not even creating it? :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!