I hate to beat a dead horse, that said, I've gone over so many conflicting articles over the past few days in regards to the use of the singleton pattern.
This question isn't be about which is the better choice in general, rather what makes sense for my use case.
The pet project I'm working on is a game. Some of the code that I'm currently working on, I'm leaning towards using a singleton pattern.
The use cases are as follows:
a globally accessible logger.
an OpenGL rendering manager.
file system access.
network access.
etc.
Now for clarification, more than a couple of the above require shared state between accesses. For instance, the logger is wrapping a logging library and requires a pointer to the output log, the network requires an established open connection, etc.
Now from what I can tell it's more suggested that singletons be avoided, so lets look at how we may do that. A lot of the articles simply say to create the instance at the top and pass it down as a parameter to anywhere that is needed. While I agree that this is technically doable, my question then becomes, how does one manage the potentially massive number of parameters? Well what comes to mind is wrapping the different instances in a sort of "context" object and passing that, then doing something like context->log("Hello World"). Now sure that isn't to bad, but what if you have a sort of framework like so:
game_loop(ctx)
->update_entities(ctx)
->on_preupdate(ctx)
->run_something(ctx)
->only use ctx->log() in some freak edge case in this function.
->on_update(ctx)
->whatever(ctx)
->ctx->networksend(stuff)
->update_physics(ctx)
->ctx->networksend(stuff)
//maybe ctx never uses log here.
You get the point... in some areas, some aspects of the "ctx" aren't ever used but you're still stuck passing it literally everywhere in case you may want to debug something down the line using logger, or maybe later in development, you actually want networking or whatever in that section of code.
I feel like the above example would much rather be suited to a globally accessible singleton, but I must admit, I'm coming from a C#/Java/JS background which may color my view. I want to adopt the mindset/best practices of a C++ programmer, yet like I said, I can't seem to find a straight answer. I also noticed that the articles that suggest just passing the "singleton" as a parameter only give very simplistic use cases that anyone would agree a parameter would be the better way to go.
In this game example, you probably wan't to access logging everywhere even if you don't plan on using it immediately. File system stuff may be all over but until you build out the project, it's really hard to say when/where it will be most useful.
So do I:
Stick with using singletons for these use cases regardless of how "evil/bad" people say it is.
Wrap everything in a context object, and pass it literally everywhere. (seems kinda gross IMO, but if that's the "more accepted/better" way of doing it, so be it.)
Something completely else. (Really lost as to what that might be.)
If option 1, from a performance standpoint, should I switch to using namespace functions, and hiding the "private" variables / functions in anonymous namespaces like most people do in C? (I'm guessing there will be a small boost in performance, but then I'll be stuck having to call an "init" and "destroy" method on a few of these rather than being able to just allow the constructor/destructor to do that for me, still might be worth while?)
Now I realize this may be a bit opinion based, but I'm hoping I can still get a relatively good answer when a more complicated/nested code base is in question.
Edit:
After much more deliberation I've decided to use the "Service Locator" pattern instead. To prevent a global/singleton of the Service Locator I'm making anything that may use the services inherit from a abstract base class that requires the Service Locator be passed when constructed.
I haven't implemented everything yet so I'm still unsure if I'll run into any problems with this approach, and would still love feedback on if this is a reasonable alternative to the singleton / global scope dilemma.
I had read that Service Locator is also somewhat of an anti-pattern, that said, many of the example I found implemented it with statics and/or as a singleton, perhaps using it as I've described removes the aspects that cause it to be an anti-pattern?
Whenever you think you want to use a Singleton, ask yourself the following question: Why is it that it must be ensured at all cost that there never exists more than one instance of this class at any point in time? Because the whole point of the Singleton pattern is to make sure that there can never be more than one instance of the Singleton. That's what the term "singleton" is all about: there only being one. That's why it's called the Singleton pattern. That's why the pattern calls for the constructor to be private. The point of the Singleton pattern is not and never was to give you a globally-accessible instance of something. The fact that there is a global access point to the sole instance is just a consequence of the Singleton pattern. It is not the objective the Singleton pattern is meant to achieve. If all you want is a globally accessible instance of something, then use a global variable. That's exactly what global variables are for…
The Singleton pattern is probably the one design pattern that's singularly more often misunderstood than not. Is it an intrinsic aspect of the very concept of a network connection that there can only ever be one network connection at a time, and the world would come to an end if that constraint was ever to be violated? If the answer is no, then there is no justification for a network connection to ever be modeled as a Singleton. But don't take my word for it, convince yourself by checking out page 127 of Design Patterns: Elements of Reusable Object-Oriented Software where the Singleton pattern was originally described…😉
Concerning your example: If you're ending up having to pass a massive number of parameters into some place then that first and foremost tells you one thing: there are too many responsibilities in that place. This fact is not changed by the use of Singletons. The use of Singletons simply obfuscates this fact because you're not forced to pass all stuff in through one door in the form of parameters but rather just access whatever you want directly all over the place. But you're still accessing these things. So the dependencies of your piece of code are the same. These dependencies are just not expressed explicitly anymore at some interface level but creep around in the mists. And you never know upfront what stuff a certain piece of code depends on until the moment your build breaks after trying to take away one thing that something else happened to depend upon. Note that this issue is not specific to the Singleton pattern. This is a concern with any kind of global entity in general…
So rather than ask the question of how to best pass a massive number of parameters, you should ask the question of why the hell does this one piece of code need access to that many things? For example, do you really need to explicitly pass the network connection to the game loop? Should the game loop not maybe just know the physics world object and that physics world object is at the moment of creation given some object that handles the network communication. And that object in turn is upon initialization told the network connection it is supposed to use? The log could just be a global variable (or is there really anything about the very idea of a log itself that prohibits there ever being more than one log?). Or maybe it would actually make sense for each thread to have its own log (could be a thread-local variable) so that you get a log from each thread in the order of the control flow that thread happened to take rather than some (at best) interleaved mess that would be the output from multiple threads for which you'd probably want to write some tool so that you'd at least have some hope of making sense of it at all…
Concerning performance, consider that, in a game, you'll typically have some parent objects that each manage collections of small child objects. Performance-critical stuff would generally be happening in places where something has to be done to all child objects in such a collection. The relative overhead of first getting to the parent object itself should generally be negligible…
PS: You might wanna have a look at the Entity Component System pattern…
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
When should we use the Singleton pattern and why?
http://sites.google.com/site/steveyegge2/singleton-considered-stupid
Why is the Singleton so attractive? I'll be the first to admit: I liked it too. No, scratch that - I loved the Singleton. It felt like an old friend from the moment I laid eyes on it. It was simple and beautiful.
I'll tell you why: it's because the Singleton pattern is a throwback to non-OO programming. It's a lifeline for people who didn't understand a single word that the Gang of Four were trying to say. I don't know how it got in there in the first place -- some political OOPSLA pressure, no doubt -- but it doesn't belong in there. It's Evil...
Here's the "short" summary...
a) I haven't covered even a tenth of the issues. But I'll name a few of them.
b) One is memory management; a Singleton is basically just a memory leak, if nobody is going to be using it for a while. But you have no idea when to deallocate it, because nobody's going to call you and say "nobody's going to be using you for a while!"
Besides, you can't tell who has kept around references to your Singleton instance, since you were pretty blase about handing it out, weren't you? (Note: Java's weak references can help with this issue).
c) Speaking of memory leaks, what if your Singleton has a handle to some limited resource, like a database or file handle? I guess you get to keep that sucker open until your program ends. Thank God C++ programs never last longer than about 10 minutes before crashing, usually from running out of resources, or from trying to access a Singleton that someone freed.
d) Another issue is that the Singleton design is syntactically noisy; most languages don't support it (well, Ruby does, sadly, but that was probably before Matz knew any better), so you have to stick in boilerplate code not only in the Singleton, but in everyone who uses it.
e) Then there's the subclassing thing. It's almost impossible to subclass a Singleton, and if you manage it, then you shouldn't have been using a Singleton in the first place. You don't even want to go there. I've walked roads that I dare not recount. Just pretend you can't do it, and you'll save yourself amazing amounts of pain.
f) static methods are as flexible as granite. Every time you use one, you're casting part of your program in concrete. Just make sure you don't have your foot jammed in there as you're watching it harden. Someday you will be amazed that, by gosh, you really DO need another implementation of that dang PrintSpooler class, and it should have been an interface, a factory, and a set of implementation classes. D'oh!
Don't suppose that's all. There are many other problems. For instance, try adding multithreading in and see what happens. Well, I'll tell you what happens: half the time, you get a Doubleton or a Tripleton, unless you're a synchronization expert, and having a Tripleton is about as desirable as having three Balrogs show up at your tea party. And even if you're a synchronization expert and get the double-check idiom right, you've still got one Balrog to deal with, and they're no picnic.
But these problems all fade into insignificance compared to the Big One, which is that the Singleton "pattern" encourages you to forget everything you know about OO design, since OO is hard, and procedural is easy...
Java Runnable is the best example of the Singleton Pattern. When you want to add a restriction which does not allow you to create more than a single instance of a particular class then it is better to implement a Singleton Pattern.
Key points to implement singleton :
Private Constructor
Static Private Instance Variable of Singleton class itself
Public getter method only at very first time it will initialize above variable, and always return same instance of a Singleton class.
class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance=null){
instance=new Singleton();
}
return instance;
}
........
}
And for thread safety :
getInstance() needs to be synchronized.
If you have a situation when exactly one object is needed to coordinate actions across the system, then you can use this pattern. A good example of this is the Facade, that is, Facades can be implemented as singletons because often one Facade object is needed across the system.
But in general, it's usually a bad practice and should be avoided, one big reason is it greatly inhibits extensibility.
In theory: when you need to restrict the instantiation of an object to one instance. In practice: never.
As said the intention of a singleton pattern is to ensure that a single instance of a class is instantiated.
The singleton pattern is considered as one of the "bad" patterns in the GOF pattern catalog since the singleton leads to coupling in code and makes (unit) testing of code hard. The latter point is not 100% true in (most) dynamic/loosely typed languages because you can monkey patch code.
Let's take a look at coupling: Every code piece that uses the Singleton is coupled directly to the implementation of the Singleton. This is hard/impossible to mock and since Singletons are often used for infrastructure services like a database access layer the unit that you want to test is coupled to the concrete implementation of the database access layer. But for a unit test you do not want to hit the database, you want to have some mock data access layer. You end up in a situation where you ask yourself why you used the singleton pattern.
I'd recommend the singleton pattern only for "simple" software but as we all know software has a tendency to grow. To start simple and end complex after some years.
When you don't want to create multiple instances of same type you need to go for singleton. But the same can be achieved if you use Static Classes. So the point here is it's not the only one instance but the control over instance creation, thus avoiding unneccessary consumption of precious resources.
Think of everything where more than one instance would be an error (inconsistence). THis could be an Application object (root object for a app) or a application wide securityManager etc. The singleton is just a way to enforce that at class can only have one instance.
The Singleton pattern is about to ensure a class has only one instance, and provide a global point of access to it.
When you want a bunch of different objects to be able to make reference to one single object. Maybe they want to all use the same PhysicsEngineDude or something... You don't want different objects having different physics models when they live in the same world!
When you just need one instance from a class. One of the best example is the logger. You just need an instance of it.
When only one instance from a class that is needed in the system.Since it has only one instance, so you can rigidly decide how the users can get access to it.
In software engineering, the singleton pattern is a design
pattern that restricts the Instantiation of a class to one object.
This is useful when exactly one object is needed to coordinate
actions across the system.
Application needs one, and only one, instance of an object.
Additionally, lazy initialization and global access are necessary.
More here...
http://www.dzone.com/links/r/java_ee_singleton_design_pattern_introduction.html
I've been developing a game with my company for a good few years now. However recently we have been improving the base systems of our game to make future additions easier. One change we did was add Resource Managers instead of manually loading in information inside our Screen classes which are essentially game states. We decided to implement this as a singleton. I however am aware of the controversy in the use of singletons in the programming community.
I will give an example of how we use our Font Manager down bellow. And I would like to know whether in this case a singleton is acceptable or whether you would recommend some other method.
mTextToBeDrawn.setFont(FontManager::GetInstance()->GetFont("Default"));
I am open to all suggestion and I will explain the current OOP design in order for a deeper understanding of the system. Every Manager extends from a base class called Manager with generic Add and Remove Methods. The Add and Remove Methods are then implemented in the derived classes. These classes only require one instance ever as the game will only require one State Manager, Font Manager and so forth. So should I use singletons or should I use another method in order to create better code.
Often in the programming community we hear "using X is bad" or "using X is good", but just labeling something as bad or good doesn't at all explain its' strengths and weaknesses or how something might be problem or how it could be used appropriately. If you don't understand why something might be bad, chances are you won't notice it when it creeps up in other forms or with different names.
In your example of the singleton, I would do a little research to identify criticisms and pitfalls of using of singletons and evaluate whether they will be a problem for you.
The biggest two concerns for me are:
Singletons introduce global data and global state.
With global data, access and modification can happen all over the code which makes bugs difficult to track down, and it can more easily get in messed up states. Often singletons are a result of poor design.
Singletons are often not thread safe.
In some applications the pitfalls don't really become a problem. In the Cocoa/Objective-C world Apple occasionally uses Singletons to solve problems which are, in my opinion, completely fit for the job. Some of their usages are similar to what you describe such as image management/caching.
You can read more here What is so bad about singletons?
I often find myself in situations where objects need to communicate between each other. For example, a button might need to talk to various textboxes. Would it be proper to simply construct each widget with a pointer to the container for all of them? Would it be better to give it a pointer to a resource container map where the object can locate another object by string or something? This area has always been very vague to me. I could easily implement everything I want to do if I just constructed objects with pointers to containers of every other object, but that seems wrong. In the case of a widget, would it actually just be more proper if the widget knew nothing about the outside world and instead its action listeners were constructed with resource access?
Thanks
I understand that it is a bad idea but what are some solutions in these situations eg: good design patterns?
Any object should know as little as possible about things outside itself. What you are describing sounds alot like the ani-pattern often referred to as a 'God object'
You get better de-coupling if you use messages/events.
objects with pointers to containers of every other object, but that seems wrong.
And why do you think it is wrong?
Usually you will not just need to send messages but to do something like navigation/enumeration.
For example HTML DOM tree consists of nodes where each node contains [weak] reference to its parent. Without such reference operations like nextSibling() are just impossible.
So answer depends on set of other operations you will want to implement there.
The answer depends on how long the objects might live and how long the pointers might stick around. Anything which might change needs to go through a directory service. If the target's lifetime is short enough, you might even need to have the directory service place a hold on the target.
DON'T DO THAT!
No, seriously, your idea is analogous to the singleton pattern, with the difference that you have just one instance per "name" instead of per type.
You can collect a bunch of bad things about your idea by seeing what's wrong with singletons.
Why would a button in a dialog(?) want to know how many other objects there are in the dialog?
When the button is pressed, it sends a message to its owner. The owner will then have to coordinate the action between the widgets it owns. You don't want to change the code for you OK-button when the dialog gets another listbox, do you?
You could use dependency injection to pass the pointers you need. That way you make the dependencies explicit. http://en.wikipedia.org/wiki/Dependency_injection
This approach gives you a lot of advantages - unit testing is much easier when you don't have global state, god objects and so on. Also when new guy comes to the team, he can see what are the dependencies of a class - you make it explicit in constructor, so no magic like "you must first create this singleton to use that object or it will crash". This approach reduces coupling, thus making reuse easier.
IMO it is not possible to make every class independent of all the others (you ask if it is better when widget does not know anything about outside world). While this removes coupling making code reuse easier it also is very hard to do and leads to lot more coding.
On the other hand it is a bad idea to pursue some ideology "just because" without understanding why. Maybe in your case advantages of OOP are not worth writing additional code. If you can see that you will finish your application much quicker with "god object" then I would say "go for it".
IMO it is not as easy as "never create singletons and god objects". You must decide if additional time spent on passing all the references explicitly pays back in future.
Personally I always choose what is appropriate for program I write. It is not unusual for me to consciously break some OOP rules. Remember there are also other guidelines - I like KISS.
I keep hearing that global variables should never be used, but I have a tendency to dismiss "never" rules as hot-headed. Are there really no exceptions?
For instance, I am currently writing a small game in c++ with SDL. It seems to me to make a lot of sense to have a global variable with a pointer to the screen buffer, because all the different class that represent the different type of things in the game will need to blit to it, and there is only one screen buffer.
Please tell me if I am right that there are exceptions, or if not then:
Why not, or what is so bad about them that they should be avoided at all costs (please explain a little bit)
How can this be achieved, preferably without having to pass it to every constructer to be stored internally until needed, or to every call to a paint() request.
(I would assume that this question had been asked on SO before, however couldn't find what I need (an explanation and workaround) when searching. If someone could just post a link to a previous question, that could be great)
We tell students never to use global variables because it encourages better programming methods. It's the same reason we tell them not to use a goto statement. Once you're an accomplished programmer then you can break the rules because you should know when it's appropriate.
Of course there are exceptions. I personally can't think of a single situation where a goto is the right solution (or where a singleton is the right solution), but global variables occasionally have their uses. But... you haven't found a valid excuse.
Most objects in your game do not, repeat, not need to access the screen buffer. That is the responsibility of the renderer and no one else. You don't want your logger, input manager, AI or anyone else putting random garbage on the screen.
And that is why people say "don't use globals". It's not because globals are some kind of ultimate evil, but because if we don't say this, people fall into the trap you're in, of "yeah but that rule doesn't apply to me, right? I need everything to have access to X". No, you need to learn to structure your program.
More common exceptions are for state-less or static objects, like a logger, or perhaps your app's configuration: things that are either read-only or write-only, and which truly needs to be accessible from everywhere. Every line of code may potentially need to write a log message. So a logger is a fair candidate for making global. But 99% of your code should not even need to know that a screen buffer exists.
The problem with globals is, in a nutshell, that they violate encapsulation:
Code that depends on a global is less reusable. I can take the exact same class you're using, put it in my app, and it'll break. Because I don't have the same network of global objects that it depends on.
It also makes the code harder to reason about. What value will a function f(x) return?
It obviously depends on what x is. But if I pass the same x twice, will I get the same result? If it uses a lot of globals, then probably not. Then it becomes really difficult to just figure out what it's going to return, and also what else it is going to do. Is it going to set some global variable that's going to affect other, seemingly unrelated, functions?
How can this be achieved, preferably without having to pass it to every constructor to be stored internally until needed
You make it sound like that's a bad thing. If an object needs to know about the screen buffer, then you should give it the screen buffer. Either in the constructor, or in a later call. (And it has a nice bonus: it alerts you if your design is sloppy. If you have 500 classes that need to use the screen buffer, then you have to pass it to 500 constructors. That's painful, and so it's a wake-up call: I am doing something wrong. That many object shouldn't need to know about the screen buffer. How can I fix this?`)
As a more obvious example, say I want to calculate the cosine of 1.42, so I pass 1.42 to the function: cos(1.42)
That's how we usually do it, with no globals. Of course, we could instead say "yeah but everyone needs to be able to set the argument to cos, I'd better make it global". Then it'd look like this:
gVal = 1.42;
cos();
I don't know about you, but I think the first version was more readable.
Like any other design decision, using global variables has a cost. It saves you having to pass variables unnecessarily, and allows you to share state among running functions. But it also has the potential to make your code hard to follow, and to reuse.
Some applications, like embedded systems, use global variables regularly. For them, the added speed of not having to pass the variable or even a pointer into the activation record, and the simplicity, makes it a good decision [arguably]. But their code suffers for it; it is often hard to follow execution and developing systems with increasing complexity becomes more and more difficult.
In a large system, consisting of heterogeneous components, using globals may become a nightmare to maintain. At some point you may need a different screen buffer with different properties, or the screen buffer may not be available until it's initialized meaning you'll have to wrap every call to it with a check if it's null, or you'll need to write multithreaded code, and the global will require a lock.
In short, you are free to use global vars while your application is small enough to manage. When it starts to grow, they will become a liability, and will either require refactoring to remove, or will cripple the programs growth (in terms of capability or stability). The admonition not to use them stems from years of hard-learned lessons, not programmer "hot-headedness".
What if you want to update your engine to support dual screen? Multiple displays are becoming more and more common all the time. Or what if you want to introduce threading? Bang. How about if you want to support more than one rendering subsystem? Whoopsie. I want to pack my code as a library for other people or myself to re-use? Crap.
Another problem is that the order of global init between source files is undefined, making it tricky to maintain more than a couple.
Ultimately, you should have one and only one object that can work with the screen buffer - the rendering object. Thus, the screen buffer pointer should be part of that object.
I agree with you from a fundamental point of view - "never" is inaccurate. Every function call you make is calling a global variable - the address of that function. This is especially true for imported functions like OS functions. There are other things that you simply cannot unglobal, even if you wanted to - like the heap. However, this is most assuredly not the right place to use a global.
The biggest problem with globals is that if you later decide that a global wasn't the right thing to do for any reason (and there are many reasons), then they're absolutely hell to factor out of an existing progam. The simple fact is that using a global is just not thinking. I can't be bothered to design an actual rendering subsystem and object, so I'm just gonna chuck this stuff in a global. It's easy, it's simple, and not doing this was the biggest revolution in software programming, ever, and for good reason.
Make a rendering class. Put the pointer in there. Use a member function. Problem solved.
Edit: I re-read your OP. The problem here is that you've split your responsibilities. Each class (bitmap, text, whatever) should NOT render itself. It should just hold the data that the master rendering object needs to render it. It's a Bitmap's job to represent a bitmap - not to render a bitmap.
Global variables can change in unexpected ways, which is usually not what you want. The state of the application will become complex and unmaintainable. Very easy to make something wrong. Especially if someone else is changing your code;
Singleton might be a better idea. That would at least give you some encapsulation in case you need to make extensions in the future.
One reason not to use global variables is a problem with namespaces (i.e. accidentally using the same name twice);
We do often use global (to namespace) constants at work which is considered normal, as they don't change (in unexpected ways) and it is very convenient to have them available in multiple files.
If the screen buffer is shared between lots of different pieces of code, then you have two options:
1) Pass it around all over the place. This is inconvenient, because every piece of code that uses the screen buffer, even indirectly, needs to be laboriously indicated as such by the fact that this object is passed through the call stack.
2) Use a global. If you do this, then for all you know any function at all in your entire program might use the screen buffer, just by grabbing it from the global[*]. So if you need to reason about the state of the screen buffer, then you need to include the entire program in your reasoning. If only there was some way to indicate which functions modify the screen buffer, and which cannot possibly ever do so. Oh, hang on a second...
This is even aside from the benefits of dependency injection - when testing, and in future iterations of your program, it might be useful for the caller of some function that blits, to be able to say where it should blit to, not necessarily the screen.
The same issues apply as much to singletons as they do to other modifiable globals.
You could perhaps even make a case that it should cost you something to add yet another piece of code that modifies the screen buffer, because you should try to write systems which are loosely coupled, and doing so will naturally result in fairly few pieces of code that need to know anything at all about the screen in order to do their job (even if they know that they're manipulating images, they needn't necessarily care whether those images are in the screen buffer, or some back buffer, or some completely unrelated buffer that's nothing to do with the screen). I'm not actually in favour of making extra work just to punish myself into writing better code, but it's certainly true that globals make it quite easy to add yet another inappropriate wad of coupling to my app.
[*] Well, you may be able to narrow it down on the basis that only TUs that include the relevant header file will have the declaration. There's nothing technically to stop them copy-and-pasting it, but in a code base that's at all well regulated, they won't.
The reason i never do it is because it creates a mess. Imagine setting ALL unique variables to globals, you would have an external list the size of a phonebook.
Another reason could be that you don't know where it is initialized or modified. What if you accidently modify it at place X in file Y? You will never know. What if it isn't initialized yet? You will have to check everytime.
if (global_var = 0) // uh oh :-(
if (object->Instance() = 0) // compile error :-)
This can both be fixed using singletons. You simply cant assign to a function returning you the object's adress.
Besides that: you don't need your screen buffer everywhere in your application, however if you want to: go ahead, it doesn't make the program run less good :-)
And then you still have the namespace problem but that at least gives you compile errors ;-)
"Why not": global variables give you spaghetti information flow.
That's the same as goto gives you spaghetti control flow.
You don't know where anything comes from, or what can be assumed at any point. The INTERCAL solution of introducing a come from statement, while offering some initial hope of finally being sure of where control comes from, turned out to not really solve that problem for goto. Similarly, more modern language features for tracking updates to global variables, like onchangeby, have not turned out to solve that problem for global variables.
Cheers & hth.,
Global variables (and singletons, which are just a wrapper around a global variable) can cause a number of problems, as I discussed in this answer.
For this specific issue -- blittable objects in a game kit -- I'd be apt to suggest a method signature like Sprite::drawOn(Canvas&, const Point&). It shouldn't be excessive overhead to pass a reference to the Canvas around, since it's not likely to be needed except in the paint pathway, and within that pathway you're probably iterating over a collection anyway, so passing it in that loop isn't that hard. By doing this, you're hiding that the main program has only one active screen buffer from the sprite classes, and therefore making it less likely to create a dependency on this fact.
Disclaimer: I haven't used SDL itself before, but I wrote a simple cross-platform C++ game kit back in the late '90s. At the time I was working on my game kit, it was fairly common practice for multi-player X11-based games to run as a single process on one machine that opened a connection to each player's display, which would quite efficiently make a mess of code that assumed the screen buffer was a singleton.
In this case a class that provides member functions for all methods that need access to the screen buffer would be a more OOP friendly approach. Why should everyone and any one have uncontrolled access to it!?
As to whether there are times when a global is better or even necessary, probably not. They are deceptively attractive when you are hacking out some code, because you need jump through no syntactic hoops to access it, but it is generally indicative of poor design, and one that will rapidly atrophy inter maintenance and extension.
Here's a good read on the subject (related to embedded programming, but the points apply to any code, it is just that some embedded programmers thing they have a valid excuse).
I'm also curious to hear the precise explanation, but I can tell you that the Singleton pattern usually works pretty well to fill the role of global variables.
I have a few classes in a project that should be created only once.
What is the best way to do that?,
They can be created as static object.
Can be created as singleton
Can be created as global.
What is the best design pattern to implement this?
I am thinking of creating all classes as singleton, but that would create lot of singletons. Is it good programming practice to have lot of singletons?
What are the pros and cons for using singletons?
Take a look at Steve Yegge's blog post about this - Singleton Considered Stupid
If they only need to be created once, that doesn't mandate they should be singletons.
If X is a singleton, it's implied there is one instance.
If X has one instance, that doesn't mean it should be a singleton.
Use a singleton if you require there be only one instance of the class, and that it be globally accessible. In your case, simply only needing one isn't reason enough. Globals are bad, singletons are glorified globals.
Most often, you don't need them. You'll see it a lot in bad code because of the very mentality: I only need one, that must mean I should make it singleton! (Wrong) For example, I've finished the technical design of the most powerful game engine I've ever done to date. It has 2 singletons, for memory and threading. A very large project, and I only have two!
More context would help us give you better information.
I suggest you look at some of the videos and articles that Miško Hevery of Google has done. First a video: "Clean Code Talks: Global State and Singletons" and his blog.
The general concensus is that Singletons are OK in a few rare instances, for example logging, but in most other situations you want to use dependency injection. Singletons make it harder to test your code and they hide dependencies so that your classes cannot be instantiated easily in isolation.
Singletons have a few problems -- they're hard to test, hard to replace, and hard to extend. There's usually a better way.
One of my favourite articles on the singleton is Singletons are Pathological Liars by Miško Hevery. Essentially, they encourage "hidden" behaviour that is very hard to learn and test.
There are projects where you can't practically avoid using globals. All kinds of service locators or dependency-injection frameworks still rely on global (not always static variable, but always global of some sort) storage of objects.
However, singletons are a sign of a problem:
First, singleton as a canonical pattern doesn't go well with interfaces and abstraction. It can be fixed though - accessing it through factory.
Worse, singletons are inflexible - they don't have any means of identifying object beyond its type. ( Well, in C++ they do through templates, but it's a different story). In that sense they are actually worse than static variables. In the long run it pays off using a framework where many instances of the same type can be accessed.
And most importantly, lots of singletons means lots of distant relationships between objects. Which means your system is probably more complex than it needs to be and will be much harder to develop, test and manage. Simply switching to locators or DI won't help there, it's a matter of underlying design principles.
A singleton is effectively global state. If you're going to create lots of singletons you're going to create lots of global state, only in won't necessarily look like global state.
This makes it hard to do things like build unit tests, provide mock classes and reuse code because its really easy to
couple the current state to a function. i.e. function foo is only valid when class X is in state Z, otherwise it doesn't work.
It's also problematic to build a thread safe singleton correctly.
Singletons can be good for coordinating access to a resource, particularly one that doesn't have much state and is expensive to construct.
So why do you think you need lots of singletons? you may get better responses if you ask about your problem domain and what issue you are hitting.
In programming there are no silver bullets. Making every class a singleton will not magically make your code "better". Singletons are a tool for that solve a specific problem I studying more about singletons.
To use singleton pattern in your project should be a well thought out and careful design decision, because its a one way track with very little scope for backtracking. I have practically used it in one of my project for a commercial product in a multithreading environment and faced multitude of problems. But this doesn't mean it's an untouchable pattern. The point is anything which can be achieved with singleton can be achieved without it, with less hassles and complexity. For more on this you can track this question I asked some months back. It has interesting links and insight into the singleton pattern