For desktop application that is. This is just a general question that maybe only need general answers.
In a scenario, where you need one central global point of access across the codebase, singletons are a good alternative for global variables. We can call a singleton as a lazily initialized global class which is useful when you have large objects — memory allocation can be deferred till when it's actually needed.
The Singleton pattern is basically just a lazily initialized global variable. It ensures that the class has one instance and that instance is globally accessible. However, do not confuse Singleton design pattern with single instances.
The Singleton pattern ensures that only one instance of a class will be created and provides a global point of access to it. Any global variables that are required can then be placed within this class and accessed wherever they are needed.
Also, strict mode will prevent us from creating global variables accidentally. So if we have: 'use strict'; count = 10; then we'll get an error.
A static class with static data members? But who cares. Static data members are just global variables with more politically correct packaging.
Don't let fashion override your common sense. There's nothing wrong with using a plain old global variable. The singleton pattern is often overkill and annoying to type, and annoying when you are single stepping through code to debug it.
Assuming you are using C/C++, I would recommend that you not have global variables that are class instances that allocate memory from the heap. They will make it harder for you to use tools that check for memory leaks. Declare the global as a pointer, new it at the beginning of main(), delete it at the end.
EDIT AFTER 6 COMMENTS: Think of logging. Wouldn't you want to be able to write a line to your log from anywhere in your app? How concretely do you accomplish that without there being something globally visible to do that logging? If you want something globally visible, then go ahead and make it globally visible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With