Skip to main content
GameDev.net gamedev.net
🔒 Locked

Singleton purposes

Started by SpaceRogue Jul 15, 2003 at 7:32 PM 21 replies 1.4k views
Original Post
SpaceRogue
SpaceRogue
What is the true purpose of a singleton? I keep reading that using them as a replacement for global variables is bad. Ok, so that eliminates one possible use. What's left? Simplistically, a singleton is just a class that allows only one instance, but what are we really trying to accomplish by using them? I can create one object of a class and then simply refrain from creating more. Does that accomplish the same thing? Are we trying to prevent people from accidentally creating more, or from purposefully circumventing the one instance limit? Additionally: Should a singleton methodology be eaily applied to existing classes or should a class be designed to be a singleton from the ground up? (I ask because I have seen singleton templates and base classes...) What do you think?
andromeda
andromeda
I guess the idea is to have a class where it is IMPOSSIBLE to have more than one instance of it, even if you try to make more.

But yes, I agree with you, I don''t really think it makes all that much sense. To me, singletons are ugly, and pretty much a hack. Seems to me if the programmer can''t remember not to create more than one object, his program deserves to crash.
SpaceRogue
SpaceRogue
Anon: I'm looking for some discussion on Singletons and their uses. The fact that Mr. Lamothe doesn't want me to use them doesn't mean much to me.

Edit: Sorry, I'm not trying to sound harsh...I welcome any advice. Sometimes however I wonder if Lamothe is stuck in the eighties.

[edited by - SpaceRogue on July 15, 2003 9:14:29 PM]
SpaceRogue
SpaceRogue
quote:
Original post by andromeda
Seems to me if the programmer can''t remember not to create more than one object, his program deserves to crash.


Hehe, I''ve thought that too. Still I''m open to the possibility that they have their uses. Perhaps in an environment where someone other than the original programmer wouldn''t necessarily know not to create more than one? Hmm...

Deyja
Deyja
Singletons have a great many wonderfull features. There are many things that there are logically only one of - like your display.

A singleton is, essentially, just a global, with all the problems fixed.
You can define the order of singleton construction, you cannot define the order of global construction.

Okay. So. That''s really all I can think of at the moment; but consider this: You can also have a multi-ton. You want to have five, and never more then five? A multi-ton can enforce that, a global can''t.
SpaceRogue
SpaceRogue
Anon: Quite the contrary, I'm not spending time coding them, just discussing them.

I've come up with my own extremely simple Singleton implmentation that is easily derived from, and handles both static initialization and deinitialization order with no problems. Dependencies among multiple singletons (of different types obviously) are also easily (and automatically) handled.

I'm just curious as to other people's opinions on them...

[edited by - SpaceRogue on July 15, 2003 9:27:54 PM]
JohnBolton
JohnBolton
quote:
Original post by SpaceRogue
What is the true purpose of a singleton?



The true purpose of a singleton is to provide GemeDev.net with a topic that can (and will) be debated endlessly. Every forum needs a few of those topics in order to give members a reason for coming back.

Some similar topics:

1. What is the fastest way to implement sin/cos/sqrt/abs...?
2. Any topic dealing with optimization.
3. OpenGL vs Direct3D
4. "I''m looking for a team of people to work on an MMORPG with me."
5. The value of OOP.
6. new/delete issues
7. Quaternions vs matrices
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
UltimaX
UltimaX
I use them in my game engine to have a global instance of a certain class.

For example: (EDIT: Ignore the quotes suppose to <>, HTML tag this is not )
class XINTERFACE : public XGBLINTERFACE"XINTERFACE"
{
}
#define GINTERFACE XINTERFACE::GetGBLI()

The interface creates the game window and handles the active rendering engine (Thats in a .dll). So if the rendering engine is Direct3D, I could do specific Direct3D stuff in say a font class.

Instead of:
void CreateFont(LPDIRECT3DDEVICE8 Direct3DDevice)
{
//What if OpenGL is the active engine?
}

I could use:
void CreateFont(void)
{
//--This will handle either one
if(GINTERFACE.ActiveEngine == Direct3D && GD3DDEVICE != NULL)
{
//--Do Direct3D font
}
else if(GINTERFACE.ActiveEngine == OpenGL)
{
//--Do OpenGL font
}
}

It all depends what you need it for. It's not only to make sure 1 instance of a class is created.

EDIT: Part of it got cut off?

-UltimaX-

"You wished for a white christmas... Now go shovel your wishes!"

[edited by - UltimaX on July 15, 2003 9:46:23 PM]
Qatal
Qatal
quote:
Original post by Anonymous Poster
I wouldn''t worry about it. If you pick up a copy of the highly esteemed Andre Lamothe''s book: Tricks of the 3D Game Programming Gurus, you''d see that he starts out by saying to not over-OOP and just make what you need and be done with it. Ie, Singleton''s are redundant and Andre Lamothe doesn''t want you to do that.


in my opinion, mr Lamothe''s opinion on OOP is rather, umm, shall we say redundant???

OOP is, in my opinion, the greatest thing thats ever happened for programmers....thinking in an OOP kind of way simplifies a good number of things...

personally, i use singletons to allow cleaner access to large "core engine" classes, without having to use a large number of externs, etc. while they shouldnt just be used willy-nilly to replace globals, they definitely have a place in encapsulating the acquisition of key engine objects.

thats my two cents'' worth....
die or be died...i think
Raloth
Raloth
I think singletons are good for people with amnesia. Really...

"A singleton is, essentially, just a global, with all the problems fixed."

If you go through all that trouble and knowledge to make the class a singleton, shouldn''t you have the knowledge to use the same thing wisely as a global variable? I don''t mean to shoot singletons down or anything. I''m sure they must have some purpose, or else they wouldn''t have been invented. My personal view is that they are better off for libraries or something that you plan on letting others use, who might not know they are not supposed to make more than one instance. Otherwise it just wastes time when you can remember not to do it and no one would ever know the difference. Again, this is not a flame on singletons.
____________________________________________________________AAAAA: American Association Against Adobe AcrobatYou know you hate PDFs...
SpaceRogue
SpaceRogue
quote:
Original post by Raloth
My personal view is that they are better off for libraries or something that you plan on letting others use, who might not know they are not supposed to make more than one instance. Otherwise it just wastes time when you can remember not to do it and no one would ever know the difference.


I agree, it is easy to simply create a single instance if the code is entirely yours, so usage for libraries makes much more sense. I happen to think they do have uses. My reasons for my original post were not to debate whether they have any use, but rather to determine what goal we are trying to accomplish when we do use them.

Specifically: We say a singleton prevents the creation of more than one instance. Now prevent is a strong word. Do we prevent the code from compiling? Do we flag something at run time? Do we silently redirect multiple declarations to a single object? Do we try to hide raw pointers? How far do we go to prevent people working around (people copying pointers, etc.) the methods we create to ensure a singleton is accessed only through the methods we provide?

These are the questions I'm really interested in...sometimes I don't express myself very clearly I guess.

[edited by - SpaceRogue on July 15, 2003 10:00:53 PM]
TSwitch
TSwitch
(You can't insult a data structure....)

I use singletons where

1) I need to be able to define the construction & initialization of the objects (passing behind the scenes management objects, for example) because either the user either can't know about or shouldn't worry about this, and

2) I need to enforce the contract of my library. If there's only one kernel, then I don't care how much you want two of them, you're only going to get one.

Both of these are to prevent other people from being dumb. If you're the only one working on a project (ever), then, by all means, be as sloppy as you want. Just be 150% certain noone else will work on it.

For (a painful) example, I wrote a level editor for a game project the team I was in was working on. I needed it *fast*, and wrote it fast (translation: spaaaaghetti code). I didn't think anyone would ever even glance at the code, and instead I subjected EVERYONE in the team to having to wrangle my code. Seems I forgot that my level editor had to be integrated into the game itself and we also wanted to add more of these neat little stencil shapes to the level editor. Oh well..

edit: I think there is such a thing as too much OOP. Mostly, if you can do something without making 4,200,000 different objects, then that's best. Just don't overspecialize your code.

[edited by - TSwitch on July 15, 2003 10:06:48 PM]
Member of the Unban nes8bit or the White Rhino in my Basement Gets Sold to the Highest Bidder Association (UNWRBGSHBA - Not accepting new members.)Member of the I'm Glad Mithrandir Finally Found an Association that Accepts People with his Past History Association (IGMFFAAPPHA)
RomSteady
RomSteady
Regardless of what else you may thing, singletons are good for at least one major purpose: thread-safe globals. Wrap your access with a mutex and go!

Edit: Oh, and singletons are a design pattern. As such, there is no one true purpose. One must look at the pattern and see if it applies for what they are doing.

[edited by - RomSteady on July 15, 2003 10:18:27 PM]
Michael Russell / QA Manager, Ritual EntertainmentI used to play SimCity on a 1:1 scale.
SpaceRogue
SpaceRogue
Thanks to everybody who posted.

I don''t think I worded my original post very well, but then again debating the merits of singletons is probably more exciting than discussing the dry implementation details I intended.
RomSteady
RomSteady
quote:
Original post by TSwitch
(You can''t insult a data structure....)


Sure you can. You can insult anything you want. It doesn''t mean that the object of your insult will be listening, or even comprehend your insult, but it does not stop you from insulting anything in the least.

Insulting random objects can be rather entertaining. I, for example, pass the time waiting for builds to finish by insulting various forms of navel lint. [grin]

And if you can''t tell that I''m joking, you *really* need to get out more.
Michael Russell / QA Manager, Ritual EntertainmentI used to play SimCity on a 1:1 scale.
Way Walker
Way Walker
quote:
Original post by SpaceRogue
Simplistically, a singleton is just a class that allows only one instance, but what are we really trying to accomplish by using them? I can create one object of a class and then simply refrain from creating more. Does that accomplish the same thing?



No, because you could just as easily have created another.

quote:

Are we trying to prevent people from accidentally creating more, or from purposefully circumventing the one instance limit?



Closer, but I still don''t think that''s the point.

quote:

Additionally: Should a singleton methodology be eaily applied to existing classes or should a class be designed to be a singleton from the ground up? (I ask because I have seen singleton templates and base classes...)



I think this is misunderstanding at the basic purpose.

quote:

What do you think?



Note that this is all what I think, and may be wrong. I think that when people say things like "Singletons keep you from making more than one" or "Singletons only allow you to create more than one" are missing the point. It''s not that it only lets you create one; it''s that no matter how many you create, there''s still only one. There''s only one, but it can look like there''s more. Thus, singletons are more of a "behind the scenes" sort of thing. No matter how many front ends (variables/references/etc.) you create, there''s still only one back end (the singleton). This is great for polymorphism (the interface you''re using expects multiple objects, but this implementation only has one, so we make the one look like many to the interface) or implementation hiding (you''re making a resource manager. Currently you only need one, but you expect/hope to need/have more in the future. So you create one interface that won''t change, and, for now, implement with a singleton. Later, you can change the implementation such that each time a new instance is requested a new instance is made. This can also work the other way; you consolidate your multiple managers into one allowing for whole-program-optimization of resource usage.).
tententrample
tententrample
quote:
Original post by JohnBolton
quote:
Original post by SpaceRogue
What is the true purpose of a singleton?



The true purpose of a singleton is to provide GemeDev.net with a topic that can (and will) be debated endlessly. Every forum needs a few of those topics in order to give members a reason for coming back.

Some similar topics:

1. What is the fastest way to implement sin/cos/sqrt/abs...?
2. Any topic dealing with optimization.
3. OpenGL vs Direct3D
4. "I''m looking for a team of people to work on an MMORPG with me."
5. The value of OOP.
6. new/delete issues
7. Quaternions vs matrices



If I were drinking milk it would have come out of my nose.
Jedyte
Jedyte
A Singleton is just (like all programming) an abstraction.
You conceptually want only 1 instance of a class, fine, let''s enforce that in code. You don''t have to, you could just instantiate it only once.
You could also say, "I use an int to represent the height of a building" and then use int everywhere. Or you could just do
typedef int BuildingHeight 
.
It works just as well, but the abstraction makes it easier to work with. Easier = less errors = better code.

I guess this is simplifying it, but it''s to illustrate a view
And the price we paid was the price men have always paid for achieving paradise in this life -- we went soft, we lost our edge. - "Muad'Dib: Conversations" by the Princess Irulan
Yanroy
Yanroy
Here''s my idea of a singleton:

namespace MySingleton
{
int SomeSingletonFunc();
float SomeSingletonMemberVariable;
}

There are two tiny, inconsequential problems with doing it this way... one, it''s global, and two, there''s no construction/destruction.

--------------------


You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming

You are unique. Just like everybody else.

"Mechanical engineers design weapons; civil engineers design targets."
"Sensitivity is adjustable, so you can set it to detect elephants and other small creatures." -- Product Description for a vibration sensor

Yanroy@usa.com

--------------------

You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming
You are unique. Just like everybody else.
"Mechanical engineers design weapons; civil engineers design targets."
"Sensitivity is adjustable, so you can set it to detect elephants and other small creatures." -- Product Description for a vibration sensor
Wandering Relic
Wandering Relic
quote:
Original post by JohnBolton
quote:
Original post by SpaceRogue
What is the true purpose of a singleton?



The true purpose of a singleton is to provide GemeDev.net with a topic that can (and will) be debated endlessly. Every forum needs a few of those topics in order to give members a reason for coming back.

Some similar topics:

1. What is the fastest way to implement sin/cos/sqrt/abs...?
2. Any topic dealing with optimization.
3. OpenGL vs Direct3D
4. "I''m looking for a team of people to work on an MMORPG with me."
5. The value of OOP.
6. new/delete issues
7. Quaternions vs matrices





LOL, good one.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.