• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
ATC

The Singleton Pattern: To be or not to be [used]?

80 posts in this topic

[quote name='larspensjo' timestamp='1352402394' post='4998985']
Doing an implementation for a thing that there must be only one of in such a way that the design allows for multiple future extensions takes more effort. Usually you have a limited budget, and the singleton pattern is very quick and easy to implement.[/quote]
A global is even quicker and easier to implement, and is arguably less objectionable. Passing in a pointer to an instance is barely more complicated.

[quote]Testing the general purpose variant of the design may take more effort. (Yes, I know, using global instances of a singleton may also add to the testing effort, but the discussion about singletons is not the misuse of global objects).[/quote]
Singletons (and globals in general) are the anathema of testing. Anytime a class calls to a global, they escape your test harness., and you are screwed.

[quote]A generalized class can cost more CPU time. I am not saying it will, or that it really matters, just that it may be the case.[/quote]
Artificially restricting the use-cases of a class to a single instance is the path that requires additional effort here. Not enforcing those constraints is free.

[quote]The factory pattern is based on the singleton pattern. That is, it usually uses classes with a private constructor to force clients to use the factory methods.[/quote]
[b]No, just, no.[/b] If your factories are singletons, then you are doing that wrong too.

What happens when you need to dynamically replace a factory at runtime, or any of a dozen more trivial use-cases?

[quote name='trasseltass' timestamp='1352402902' post='4998989']We're not designing and delivering a composite of multiple cars.[/quote]
And when you need to instantiate multiple cars in your test harness, what then? Try telling an automotive engineer that he is designing a car of which only a single will ever be built, and no prototypes either...
2

Share this post


Link to post
Share on other sites
[quote name='trasseltass' timestamp='1352402902' post='4998989']We're not designing and delivering a composite of multiple cars.[/quote]
And when you need to instantiate multiple cars in your test harness, what then? Try telling an automotive engineer that he is designing a car of which only a single will ever be built, and no prototypes either...

If your test subject for a black box test is the entire system, e.g. the car, in what situation would you need to create multiple instances of it? Sounds like something that is dependant on the design of your test harness / test environment. I think you're confusing design with production - it should be perfectly fine to design a single system and then produce multiple instances of it.
0

Share this post


Link to post
Share on other sites
I don't have any more time for this, but it's always nice to discuss Singletons. Lots of strong opinions. :)

TBH, I never use singletons for game development. I have however seen it used for embedded software projects that are strongly linked to using UML.
0

Share this post


Link to post
Share on other sites
I am still definitely on the side of "singletons are evil" but less so than I used to be.


Avoiding globals and singletons can lead to a lot of unnecessary upfront design work. "You might need more than one down the road" is the same rhetoric that justifies layers and layers of abstraction. "But I need to make it extensible for the future!" You don't know what the requirements will be in the future. Don't waste time over-designing something that will never be used.

Another thing I've discovered is that global functions and global state are two entirely different things. I used to try to minimize dependencies by not using global functions, but really those are totally fine. It's global [i]state[/i] that's more dangerous.
2

Share this post


Link to post
Share on other sites
[quote name='et1337' timestamp='1352404863' post='4999006']
It's global state that's more dangerous.[/quote]
One could argue that it's the 'state' that is dangerous, rather than the 'global' part of it.

Stateless systems are far easier to test and prove correctness of, after all.
1

Share this post


Link to post
Share on other sites
Swiftcoder has made a very good point... dealing with multiple threads...

Now that I consider this, perhaps I can redesign the allocation process to create a dictionary of NativeMemoryManager instances indexed by the hash of thread it was created on. That way each thread in the application has its own instance. If the thread is terminated prematurely all resources could be released (EDIT: Unless another thread requires them)... Edited by ATC
0

Share this post


Link to post
Share on other sites
[quote name='ATC' timestamp='1352410081' post='4999029']
Now that I consider this, perhaps I can redesign the allocation process to create a dictionary of NativeMemoryManager instances indexed by the hash of thread it was created on. That way each thread in the application has its own instance. If the thread is terminated prematurely all resources could be released...[/quote]
And now you have designed a need for cross-thread hash container that requires explicit synchronisation... All to hang on to the Highlander rule (aka "there can only be one").

Designing additional layers of abstractions on top of flawed design patterns is not a solution [img]http://public.gamedev.net//public/style_emoticons/default/wacko.png[/img]

Edit: Also, what you are describing already exists. See [url="http://en.wikipedia.org/wiki/Thread-local_storage"]Thread Local Storage[/url]. Edited by swiftcoder
0

Share this post


Link to post
Share on other sites
I'm aware of that. But how would you suggest approaching the design then?
0

Share this post


Link to post
Share on other sites
What's wrong with the obvious solution: don't make it a singleton, don't use global state and let the client decide if it wants to synchronize access to a single allocator or use one per thread without synchronization?
0

Share this post


Link to post
Share on other sites
[quote name='swiftcoder' timestamp='1352403446' post='4998992']
A global is even quicker and easier to implement, and is arguably less objectionable.
[/quote]

A global is at least honest about what it is. You know what you're dealing with as soon as you see one. A singleton tries to dress it up in pretty syntactic sugar, which can make it seem more acceptable to some.
1

Share this post


Link to post
Share on other sites
[quote name='trasseltass' timestamp='1352404407' post='4999004']
I don't have any more time for this, but it's always nice to discuss Singletons. Lots of strong opinions. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img][/quote]
Just so you know, leaving the conversation before being convinced of the opposite side doesn't mean you won [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]

[quote]TBH, I never use singletons for game development. I have however seen it used for embedded software projects that are strongly linked to using UML.[/quote]

Embedded systems are one of few domains where you might actually encounter a legitimate singleton, but it has nothing to do with UML. UML can be a useful tool surely enough, but it seems more often than not to be a sign of government contractees or over-engineered java contraptionists, there's certainly no correlation between those that use UML and those who can actually engineer code.

The average UML diagram is about as far removed from actual code as a 3rd grader's drawing of a car is removed from the production line.

[quote name='et1337' timestamp='1352404863' post='4999006']
Avoiding globals and singletons can lead to a lot of unnecessary upfront design work. "You might need more than one down the road" is the same rhetoric that justifies layers and layers of abstraction. "But I need to make it extensible for the future!" You don't know what the requirements will be in the future. Don't waste time over-designing something that will never be used.
[/quote]
Except that singletons usually *are* extra work. You jump through hoops to ensure their "singleness" when a simple global would do the same job. Neither is a great long term solution, but if you can't be persuaded to put in the work of actually designing your code properly, I fail to see what good wrapping your global state in a single-serve, tin-foil package buys you.
2

Share this post


Link to post
Share on other sites
I'm probably gonna get creamed for saying this, but I usually use namespaces for systems that I only want one of. I've never felt the need to make a singleton. It seems to me like a complicated way of doing what a namespace does simply. TBH when I used to read about the singleton in books I would feel bad, like I was failing to understand something, because I just couldn't see why the hell anyone would want to do something like that.

That being said, I am fully aware that using a namespace to encapsulate some kind of system means that I can only have one, and I make that decision on a program-by-program basis. If it's even remotely possible that I may want more than one of something then I'll make it a class. If it turns out later that I was wrong then I can either change the class into a namespace (To un-clutter the code - I hate passing some object to every gorram thing in the program.) or just leave it as is. Edited by Khatharr
0

Share this post


Link to post
Share on other sites
What I get from this is that the right way of doing it is to pass objects to each function needing it, avoiding globals/singletons completly. But ain't there problems with that as well? Lets say I have an Input class and a Graphics class. It seems convenient that I pass the Input object to Update() and the Graphics object to Draw(), like this:

[source lang="cpp"]void Game::Update(float dt, Input* pInput)
{

}

void Game::Draw(Graphics* pGraphics)
{

}[/source]

In Game I might have a World class which also have Update() and Draw() methods. And in World there is a Player, but the Player class should be able to call a function in Graphics when a key is pressed. I can't do that in either Update() or Draw() since they only are passed one of Input and Graphics. In this case I find it really useful for one of them to global since I don't have to bother about this issue. I can see two options to solve this without the use of globals.
[list=1]
[*]Change Game::Update() and World::Update() to take a Graphics* parameter.
[*]Add a Graphics* mGraphics member variable to each class that needs it, and set it with SetGraphics(Graphics* pGraphics) on initialization (what if I forget to set it?)
[/list]
Maybe there are more options, what do you recommend doing? Edited by simpler
0

Share this post


Link to post
Share on other sites
Has anyone any thoughts on the enum Singleton in Java?

It avoids some of the problems that people have been bringing up here with the Singleton pattern - An enum in Java is an honest global, initialization is thread safe.

I've recently use this method to implement states for a finite state machine. The state doesn't store any instance data, just operates on the object that is passed to the state methods. I could do it without singletons, but it made sense to me to have one and only instance of the state logic. There is also very little extra syntax (less than even writing as a ordinary class). It seems to work really well.

[source lang="java"]public enum Singleton {
INSTANCE;

public void methodA() {
}
}[/source]


Just throwing this out there. Not saying I'm right either. I'd probably avoid Singletons like the plague if using C++.
0

Share this post


Link to post
Share on other sites
[quote name='Khatharr' timestamp='1352453741' post='4999196']
I'm probably gonna get creamed for saying this, but I usually use namespaces for systems that I only want one of.
[/quote]
I hope you won't get, or people will eventually get afraid asking things.

I am not sure I understand how the use of namespaces limits the number of instances to a maximum of 1. The purpose of the singleton pattern is to make it impossible to instantiate more than one object from global type. The purpose is also to send a message to other people messing with the source code that it is designed in such a way that it will stop working if there is more than one instance. If you declare the type in a namespace, it doesn't stop anyone from using it incorrectly.
[quote name='simpler' timestamp='1352461621' post='4999232'] What I get from this is that the right way of doing it is to pass objects to each function needing it, avoiding globals/singletons completly [/quote]
The singleton pattern and global variables are two different problems (although they tend to be misused in interesting combinations). The singleton pattern is a way to protect [b]global types[/b] from misuse, which is independent of the problem on how to use or not to use global parameters. Apart from that, I would say your design proposals are fine (depending on situation).
2

Share this post


Link to post
Share on other sites
[quote name='davepermen' timestamp='1352465741' post='4999265']
the streering wheel example shows that some people don't understand what a class is for, and what an object is for.

[CODE]
class SteeringWheel {
}

class Car {
SteeringWheel steeringWheel;
}
[/CODE]

classes are not what defines how many exists of something. that's the objects job.

if a singleton would fit my needs, i would use it. but it NEVER ever did. it's just a) limiting and b) making code look ugly. and, most importantly, c), it NEVER makes sense.
[/quote]

this.. I am amazed what length people can go to justify their laziness. Why limit yourself to 1? I have never found a single example of something that REALLY needs to be instantiated once or kittens die... never.

That steering wheel in the car example is, seriously, pathetic. Edited by kunos
0

Share this post


Link to post
Share on other sites
METADATA:

There are many times when a program needs to store and reference data that is a result of processing and that can be used again. How will you store metadata? I like to use singletons for structural/constant data/flags/metadata(temporary) instances, when the complexity of creating new instances and having it loading its data from something/somewhere doesn't worth as simply acessing it straight like cache of processors is used and Windows Registry (always in memory).
0

Share this post


Link to post
Share on other sites
[quote name='Caburé' timestamp='1352472139' post='4999297']
METADATA:

There are many times when a program needs to store and reference data that is a result of processing and that can be used again. How will you store metadata? I like to use singletons for structural/constant data/flags/metadata(temporary) instances, when the complexity of creating new instances and having it loading its data from something/somewhere doesn't worth as simply acessing it straight like cache of processors is used and Windows Registry (always in memory).
[/quote]

sorry it doesn't float at all.
It doesn't have to be a ONE! You create it ONCE, and pass it around or publish it to objects interested in it.
You are talking about trading memory for computation costs.. it doesn't have anything to do with SINGLENESS and globality of scope. Edited by kunos
0

Share this post


Link to post
Share on other sites
[quote name='kunos' timestamp='1352472507' post='4999300']
[quote name='Caburé' timestamp='1352472139' post='4999297']
METADATA:

There are many times when a program needs to store and reference data that is a result of processing and that can be used again. How will you store metadata? I like to use singletons for structural/constant data/flags/metadata(temporary) instances, when the complexity of creating new instances and having it loading its data from something/somewhere doesn't worth as simply acessing it straight like cache of processors is used and Windows Registry (always in memory).
[/quote]

sorry it doesn't float at all.
It doesn't have to be a ONE! You create it ONCE, and pass it around or publish it to objects interested in it.
You are talking about trading memory for computation costs.. it doesn't have anything to do with SINGLENESS and globality of scope.
[/quote]


Singleton is single instance. It does not necessarily mean global scope (you can create a singleton in the scope of a package, for example).
Singleton is static - that is why there is a static word in Java (and not, again, necessarily, a global pointer/variable).
If you could reraise the data of a singleton just by making a new instance without costs, what would be the reason to use static classes (singleton) - that is what I am explaining?


How would you store, for example, trigonometry tables? If you can't see that, every time you declare a public static final int, the class where you declared it becomes a singleton, conceptually: is accessible in global scope and has only one static instance - the class itself. In Java, you can even set/change static variables at runtime (but not final variables).

I just said how I like to use SingleTons : to store metadata. I didn't argue that it is the only way to do that. But.. ppl seem to be stuck in just one technique.


After all, I am posting in the wrong place, I forgot to tell that I was meaning Java as programming language. Edited by Caburé
-1

Share this post


Link to post
Share on other sites
[quote name='Caburé' timestamp='1352473348' post='4999305']
How would you store, for example, trigonometry tables?
[/quote]

class TrigonometryTables
{
...
}

[img]http://public.gamedev.net//public/style_emoticons/default/rolleyes.gif[/img]
It DOES NOT HAVE to be one. If your application only needs one, you application will instance it once and make it available to its subsystems.
In other words: why making assumptions on an application behavior if you dont have to?
2

Share this post


Link to post
Share on other sites
[quote name='kunos' timestamp='1352474390' post='4999310']
[quote name='Caburé' timestamp='1352473348' post='4999305']
How would you store, for example, trigonometry tables?
[/quote]

class TrigonometryTables
{
...
}

[img]http://public.gamedev.net//public/style_emoticons/default/rolleyes.gif[/img]
It DOES NOT HAVE to be one. If your application only needs one, you application will instance it once and make it available to its subsystems.
In other words: why making assumptions on an application behavior if you dont have to?
[/quote]

That was a rethorical question, I already knew how to create a static class in Java. You mean why don't copy/paste Sun's/Oracle's formal definitions ? Because I thought it is a forum to interchange experience (this is rethoric again), not conceptual aspects of formal oop inspired by how philosofically the real world binds into the structure of a program and how beautiful it may become, in the aspect of fitting in the common-use of objects, the reference to singleton classes within the code.

I just said how I like to use singletons: reutilization of already created metadata valid in global level,everytime, with no specific meaning (and metadata doesn't have a context specific to an object but is the result of interactions of them, having no fit within them without extra-redesign). If the topic is how pretty it fits into the aspects of OOP... the name of the topic should be changed to "why do we still need to use singletons when it is conceptually outside the formal view of the floating round world of objects, resembling old days of procedural programming?".

I just answered the topic. If it fits or not the formal definitions of a design pattern instead of what the term means by itself.. that is another issue. Edited by Caburé
0

Share this post


Link to post
Share on other sites
Global variable is already bounded in a scope.. do you mean that, when someone uses an API, all its singletons used internally must be visible for the programmer? I don't believe.

Ok. You refer a design pattern.


I was dumb and did not payed enough attention to it in the first post, in the beginning of the topic, sorry. Edited by Caburé
0

Share this post


Link to post
Share on other sites
The fact that effort has to be made to bring up reasons (or excuses!) for using a singleton should be telling you something roundabout now.

There is no valid [i]technical[/i] constraint enforcing "there can only be one" on anything (aside from Highlander ;) ) and plenty of valid reasons why having more than one is or can be useful. So why would you enforce such a restriction on your code? And at the expense of having to do extra work in order to do so? You're basically spending extra effort in order to impose an artificial restriction on yourself. Seems a wee bit nuts to me.

That's aside from the design considerations of using globals.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0