Skip to main content
gamedev.net
🔒 Locked

Why use Singletons?

Started by GamerSg 17 replies 2.4k views
Original Post
GamerSg
GamerSg
Im trying to figure out why anyone would need to go through the trouble of using Singletons. Now the magic behind Singletons is all because of the static keyword, so why not just do this in a header file: static SingletonObj g; and include the header file in all the files you require it. Then whereever you need to use it, g.whatever();
Keem
Keem
Well one reason would be that someone would still be able to come along and create another one if they wanted to. With a singleton you make your constructor ( + copy constructor ) private or protected so that there will only ever be one instance of the class no matter what people try to do. They are no trouble anyway and very useful for managers or factories etc.
Dave Hunt
Dave Hunt
quote:
Original post by GamerSg
... so why not just do this in a header file:

static SingletonObj g;

and include the header file in all the files you require it.
Then whereever you need to use it,

g.whatever();



Because that would create a separate instance of SingletonObj in every file that included the header. filea.cpp would be referencing a completely different g than fileb.cpp, etc. Clearly not the same as a singleton.
paulecoyote
paulecoyote
Because Singleton is an established pattern for software that when applied properly can give you proper life-time management - where as you cannot guarntee the time of creation when using a normal static.

It''s an acceptable way to have something global, and are usually over-seer type classes - factories of other objects, something that keeps track of one set of data (say all your directx stuff) in one place, assessible by all but having the life-time controlled.

Another reason is thread safety - something you can build in to the singleton pattern.

If you have time please look at my singleton article on code project http://www.codeproject.com/cpp/pdesingletontemplatenomfc.asp and perhaps a few lights might go on. There are other articles there too that may help you out.

Do take care when to use it though - it''s very easy to misuse (as are nasty globals on a whole!)
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
CheeseGrater
CheeseGrater
paulsdsrubbish makes some very good points about ways singletons are better that globals.

The cynic in me has to point out that many programmers use singleton''s for two other reasons, even when they don''t use any of the technical advantages.

1) They have issues with using globals, even when globals might be appropriate and singletons provide a psychological/stylistic out.

2) Singletons (and to a lesser extent some of the other design patterns) are a nifty buzzword right now, and people (esp. new developers) love saying that they used a Design Pattern at code reviews.
Darkor
Darkor
Lolz Anon''s looking for trouble. But really I have to agree when Singletons are indeed a lot of trouble to work with.

I use Singletons when it is required, not when it''s alright to. It''s easy to misuse and are just as bad as globals are. I use it when say I am creating a reusable library and have to make certain interfaces global and have only one instance.

Some classes benefit from having only one instance, but just because it can benefit from doing so doesn''t mean that it should. One example would be when a class can be controlled internally and client programmers won''t be able to create instances of it anyway.

Sure, it might need only one instance, but if it''s within your control, you can just as easily -not- make another instance. Also, you might inadvertedly create extra instances, so be sure to have explicit constructors and place your copy constructors and overloaded assignment operators in private so they can never be called without getting errors.
_the_phantom_
_the_phantom_
I''ve made use of some singletons in my current project, mainly when it makes sense (example, connection mapper class) and they are very easy to use and setup, i just inherit my utility::singtletonn class and off I go
The singleton in queston is Scott Bilas'' from Game Programming Gems 1
GamerSg
GamerSg
quote:
Original post by Dave Hunt
quote:
Original post by GamerSg
... so why not just do this in a header file:

static SingletonObj g;

and include the header file in all the files you require it.
Then whereever you need to use it,

g.whatever();



Because that would create a separate instance of SingletonObj in every file that included the header. filea.cpp would be referencing a completely different g than fileb.cpp, etc. Clearly not the same as a singleton.



Hmm, could you explain why this is the case. Why will a new instance be created even though it is static?
davepermen
davepermen
because all include does is copy-paste the code of the header, so with

//staticobj.h

static Obj obj;


//a.cpp

#include "staticobj.h"


and

//b.cpp

#include "staticobj.h"


you get


//a.cpp

static Obj obj;


and

//b.cpp

static Obj obj;


wich defines two .cpp-local (means only in the module existing) Objects type Obj.




If that's not the help you're after then you're going to have to explain the problem better than what you have. - joanusdmentia

davepermen.net

[edited by - davepermen on November 25, 2003 5:06:46 AM]
If that's not the help you're after then you're going to have to explain the problem better than what you have. - joanusdmentia
My Page davepermen.net | My Music on Bandcamp and on Soundcloud
SabreMan
SabreMan
quote:
Original post by GamerSg
Hmm, could you explain why this is the case. Why will a new instance be created even though it is static?

Because file-scope static ensures that something is local to the translation unit it is defined in. Therefore a static variable in one TU will be a distinct entity to a static variable with the same name in a different TU.

What you actually want for creating a global is extern. You provide an extern declaration in a header file, and define the variable in a single implementation file. Everywhere which includes the header file gets to fix-up against the same definition.
Dave Hunt
Dave Hunt
Yeah. What they said.
Dreddnafious Maelstrom
Dreddnafious Maelstrom
a singleton is also useful in the observance of good OOP practices.
primarily data encapsulation and hiding.

say for example you have a singleton object that you must share across many instances of another type of object. a singleton is guaranteed to be "synched-up" for all of the objects because it is in fact the very same instance for each of them.

because the many instances of objects are the only things that need to access the singleton, the singleton can be encapsulated and contained within these objects only. this prevents a client programmer from manipulating and perhaps making invalid, the information that the singleton contains. as well as hiding completely, the information and interface that would otherwise be unnecessary clutter to any object but the one that needs it.

textbook OOP.

Dredd
________________________________________

"To die with your sword still in its sheath is most regrettable" -- Miyomoto Musashi


"Let Us Now Try Liberty"-- Frederick Bastiat
paulecoyote
paulecoyote
Alot of you seem to be missing the point. A singleton is not the same as global - declaring something as static gives you no control over the life and death of that object.

IE you have no way of knowing what order statics are created - that is compiler dependant.

Also statics do not have any thread controls on them, whereas a decent implementation of a singleton does.

Right tools for the right jobs gentlemen - it''s true it can be misused and you should have a strong case for you using a global or singleton at all.

An "anti-pattern" is over-using patterns too - it''s the judious use of patterns that make them powerful.

People who are so dismissive of Singletons and prefer globals obviously have not properly looked in to them, and probably haven''t touched any of the "new fangled" OO languages such as Java or C#. Knowledge is power - keep yourself educated and give proper arguments rather then "I can''t be arsed to use them cos I don''t see the point" ;-)

Singletons can be misused the same way as globals - globals MAY have their place, but use of statics globals AND singletons should be avoided to keep your code maintable and portable to your other projects. As I said before, Singletons should be used as factories of other objects, or a central repositry of things that are shared across many objects at runtime.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
oliii
oliii
quote:
Original post by GamerSg
Oic, sometimes i forget the little things like how header files work. Thanks.


This is a nasty gotcha. So use

extern Obj Singleton;

in the header or



class Obj
{
public:
static Obj* Instance();
static Obj* Instanciate();
static Obj* DestroyInstance();

private:
Obj() {}

static Obj s_Instance;
};


Everything is better with Metal.
__fold
__fold
Singletons are popular cause they are a cool workaround on old problems. Still, I believe that singeltons are totally useless. I''ve read several articles on the subject and many of those claim that singletons should be used if you want to make sure that you only have one instance of an object (like a texture loader) and that you want to have control over the objects lifecycle.

When someone say that they want to make sure that only one object is created then there''s already some serious flaw in the design. A texture loader is a utility class that are always only created once and then you use the same solution as always. You pass a reference/pointer to the utility class to the objects that need them, you don''t use a gloabal. Isn''t this what everyone has tried to bashed into programmers heads the last 30 years?

...and you can still add a lock to the classes if you want them to be threadsafe.
SabreMan
SabreMan
quote:
Original post by Dreddnafious Maelstrom
a singleton is also useful in the observance of good OOP practices.

Not really, it just tends to give people a warm fuzzy feeling that they are engaging in "good" OO practices without providing any assurance what they are doing is actually good. Certainly, "god" classes are a common problem in s/w designs, and Singleton often heralds the presence of a god class. Generally the advice with Singleton is to avoid. If there is only one of something in the system you are modelling, then it is only by a perversion of solution domain implementation that you will end up with more than one. If that is the case, and it causes a problem to have multiple instances, then the Singleton idiom might be valid.
SabreMan
SabreMan
quote:
Original post by __fold
You pass a reference/pointer to the utility class to the objects that need them, you don''t use a gloabal. Isn''t this what everyone has tried to bashed into programmers heads the last 30 years?

Pretty much. There''s a pattern name for that too. Its called "Parameterise From Above".

Topic Locked

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

Sign in to reply to this topic.