Well i read singleton are bad because they are anti pattern. I also read that the main reason for this is the global reference to singleton, anyway:
is it always possible to avoid singleton?
If so, lets says for example i got an IOCP network and i need to initialize it once and this object needs to be constant through the entire lifetime of the software. Same comes with a class i have called "paint" where i print data into the screen.
If i didn't make a singleton of it i would still need a global variable of the current Hwnd and to initialize the object locally each time i am going to use it (really annoying).
So using singleton is a sign my design is flaw?
What can i do to avoid them?
Thanks.
is it always possible to avoid singleton?
Yes, use a global variable, or (even better) fix your design. One option to fix a design is to use some kind of inversion of control.
If you try to use OO principles, you'll see you can do without a singleton.
Its a question of which entities need access to the resource that can only be instantiated once, and when (henceforth called the resource).
If the entities that need access to this resource can be instantiated with the resource (IOC, dependency injection), then that is the best way to go, thus keeping things simple and avoiding creating a Singleton. KISS.
If, for some reason, there are entities that need access to the resource, but cant be instantiated with it, then an alternative needs to be implemented. One option is a Singleton, but another option that I like to use is a Factory. This completely encapsulates the creation of the resource, and is much more future-proof, meaning that if in the future for some reason, more than one instance of the resource can be instantiated, then its all encapsulated. You cant/shouldnt try to do this with a Singleton. Of course, internally the factory will maintain the unique instance of the resource.
There are those that would argue that if an entity cant be instantiated with the resource, then the design is bad. That can be argued, and should probably be done so an a case-by-case basis.
Related
I recently decided that a service locator would be an okay design pattern to access important managers for my game like a world manager (can spawn entities and keeps track of them) and a sound manager. However, I am not sure of the most appropriate way to have access to the service locator. I started by passing a pointer to the service locator I instanced in main, but this is becoming tedious, as I have found everything (projectiles, players, everything!) is needing it in it's arguments.
I am asking this here because I don't think that it is specific to games, but if I am wrong, just let me know.
Am I going about this pattern the wrong way?
Thanks for your time.
EDIT: Would a singleton solve this problem? They have a global point of access, but I don't think that it is the cleanest solution. Any ideas? Or would that be best?
This is a situation where using a global variable (or a Singleton) may be appropriate. You have to weigh the disadvantages of using a global variable / a singleton against the convenience of not having to pass a reference nearly everywhere. If you feel the disadvantages are unlikely to affect your design/code, then using a global variable can make your code much cleaner.
Some disadvantages of using a global variable are:
Managing the lifetime of your global can be more difficult. If you define multiple global variables in different translation units (cpp files), the order in which they are instantiated is unspecified, so they'd better not rely on each other during instantiation. One solution would be to store global pointers and instantiate the objects somewhere early in your program (e.g. in main), but then you have to make sure you don't create dangling pointers during the destruction phase of your program.
You may need to synchronize access to your global variable(s) in a multi-threaded context. With global variables it's harder to use per-thread objects (or proxies) to prevent having to synchronize access.
Additional disadvantages of a singleton can be:
Not being able to create copies of your class, e.g. for saving or undo.
Personally, I am in favour of using a single context object everywhere instead of using singletons. Have the context object provide you with functions to give you pointers/references or access to all the different services, managers, etc.
What is a good way to share an instance of an object between several classes in a class hierarchy? I have the following situation:
class texture_manager;
class world {
...
std::vector<object> objects_;
skybox skybox_;
}
I currently implemented texture_manager as a singleton, and clients call its instancing method from anywhere in the code. texture_manager needs to be used by objects in the objects_ vector, by skybox_, and possibly by other classes as well that may or may not be part of the world class.
As I am trying to limit the use of singletons in my code, do you recommend any alternatives to this approach? One solution that came to mind would be to pass a texture_manager reference as an argument to the constructors of all classes that need access to it. Thanks.
The general answer to that question is to use ::std::shared_ptr. Or if you don't have that, ::std::tr1::shared_ptr, or if you don't have that, ::boost::shared_ptr.
In your particular case, I would recommend one of a few different approaches:
One possibility is, of course, the shared_ptr approach. You basically pass around your pointer to everybody who needs the object, and it's automatically destroyed when none of them need it anymore. Though if your texture manager is going to end up with pointers to the objects pointing at it, you're creating a reference cycle, and that will have to be handled very carefully.
Another possibility is just to declare it as a local variable in main and pass it as a pointer or reference to everybody who needs it. It won't be going away until your program is finished that way, and you shouldn't have to worry about managing the lifetime. A bare pointer or reference is just fine in this case.
A third possibility is one of the sort of vaguely acceptable uses of something sort of like a singleton. And this deserves a detailed explanation.
You make a singleton who's only job is to hand out useful pointers to things. A key feature it has is the ability to tell it what thing to hand out a pointer to. It's kind of like a global configurable factory.
This allows you to escape from the huge testing issues you create with a singleton in general. Just tell it to hand out a pointer to a stub object when it comes time to test things.
It also allows you to escape from the access control/security issue (yes, they create security issues as well) that a singleton represents for the same reason. You can temporarily tell it to pass out a pointer to an object that doesn't allow access to things that the section of code you're about to execute doesn't need access to. This idea is generally referred to as the principle of least authority.
The main reason to use this is that it saves you the problem of figuring out who needs your pointer and handing it to them. This is also the main reason not to use it, thinking that through is good for you. You also introduce the possibility that two things that expected to get the same pointer to a texture manager actually get pointers to a different texture manager because of a control flow you didn't anticipate, which is basically the result of the sloppy thinking that caused you to use the Singleton in the first place. Lastly, Singletons are so awful, that even this more benign use of them makes me itchy.
Personally, in your case, I would recommend approach #2, just creating it on the stack in main and passing in a pointer to wherever it's needed. It will make you think more carefully about the structure of your program, and this sort of object should probably live for your entire program's lifetime anyway.
Imagine you have a large application project, the code is split into a range of subsystems implemented as classes derived from CBaseSubsystem.
Here already comes my first question:
Is it a good idea to organize subsystems as classes [derived from a base class]?
Then, you have your subsystem classes. Now, you will need create have instances of them somewhere. But where?
Is it a good idea to have every subsystem instance stored in a global variable, for example:
extern CEventSystem* g_EventSystem;
Where should the instances be actually created? All together in a main()-like function?
Or is it better to avoid global variables entirely and organize the instances in a CSubsystemManager class or the like?
Would using singleton classes be an appropriate approach?
Very similar to this. I'd avoid Singleton, because it is absolutely unnecessary here and brings about many other issues.
Create the instances in a main-like routine. If something needs a system, provide access to it through some means, be it a parameter passed directly to that something or a container that provides access to these systems (IE: CSubSystemManager). You likely don't need to go so far as to write CSubSystemManager.
Avoid global state, there's a reason it has a stigma.
If you need a way to access an instance of each subsystem, I would avoid using "extern" and instead go with a singleton that gives you access to an instance of CSubsystemManager. The manager itself can take care of instantiating and managing your subsystem objects.
If you want to talk theory rather than provide a concrete question then consider designing in terms of a combination of Factory and Singleton with the possibility of Strategy in subsystems which may implement a similar operation for a range of different object types.
The main subsystem Factory is itself a singleton whose purpose is I hope obvious. Use lazy evaluation to allow only required subsystem objects to be loaded as needed. You may want to consider providing each subsystem with a reference counting mechanism which will allow them to be dropped when no longer needed. Some subsystems may themselves be singletons and/or may also implement Strategy pattern to provide a particular service for a range of class types.
This service may be for example validation, rendering, serialisation etc.
The value judgement of whether it is a "good idea" to build your application in this way is not for me to say. I would rather let older wisdom speak to that.
My solution would create a combo of a singleton Registry, AbstractFactory and Factory.
//in base module
class ISubsystem{} //an interface for a subsystem
//in module code
Registry::instance()->registerFactory("subsystem1",new Subsystem1Factory());
//in user code
IFactory* factory = Registry::instance()->getFactory("subsystem1");
ISubsystem* subsystem = factory->createObject(...); //you can implement whatever policy in factory impl. (like singleton etc.)
In my project I have a series of classes where their instances are manged by some manager class, for specific reasons.
Examples would be:
CSound - Abstracts a single sound
CSoundManager - Friend of CSound,
provides factory methods for creating
CSound instances, mixes active sounds
together
Also: CFont, CFontManager (for font access per-name), CSprite, CSpriteManager (for drawing each frame), and so on.
Here my first questions already:
Is what I'm doing a specific named design-pattern?
Is it in most cases, for whatever reason, a bad idea? If yes, why?
Then, I have asked myself:
How should the objects be created and destroyed? Should I permit creating them on the stack or directly with new, or only by the methods of the corresponding manager class?
(also for destruction: delete myFont; versus. FontManager.DestroyFont( myFont );)
Sounds like you may be violating the The Single Responsibility Principle (SRP) principle.
Is the CSoundManager class responsible for creating and managing the lifetime of CSound objects, or is it in charge of mixing active sounds together? Names can tell you much, and "Manager" can be understood in too many ways...
Generally, if you want these Manager classes to handle the lifetimes of your objects, then they should most likely be the only way to instantiate these objects (i.e. private ctors in the objects). See the Factory Design Pattern, although your implementation is a bit different.
If you do this, then the client code should never call new or delete. Manually calling delete is bug-prone, and should be avoided using idioms such as RAII. In this particular case, the Manager class should manage the lifetime of objects, and therefore delete will never appear in client code.
Looks like you are using some form of Factory design pattern. Not sure what makes you feel its a bad idea.
If you are treating Manager as container of the objects then it would control the life cycle of these objects. However if your objects need to live beyond the life of Manager then you would create them with new and Manager may not be responsible for destruction.
Generally what you're implementing is a Factory Method Pattern wherein an object allocates another object. However, you are not reaping the benefits of a Factory class as you're directly tying the allocated type to the factory as opposed to allowing the factory to manage all the internals abstractly. For instance, can you do this from any file, or just the factory for that resource type (CSoundManager): new CSound();
If so, you're missing the point and you basically just have a Singleton that allocates and manages an object. Consider abstracting your resource types. If CSound and CFont derived from IResource, you could have a CResourceManager that would just take an enum or some sort of identifier for that type and reduce coupling and dependencies in your codebase. Whenever you needed to use that object you could expose the type but more likely than not you could use an abstract manager (CResourceManager) to handle those objects using common interfaces (Update(), Create(), Destroy() etc...).
For your sound manager case, remember that sounds need only be loaded once and can be instanced with a unique state. In that right, have the resource manager manage the actual resource (CSound), and the sound manager (CSoundManager) maintain discrete instances (e.g. CSoundInstance) and manage mixing (via CSoundMixer). Specialize your classes in meaningful ways that manage complexity and reduce redundancy.
I used the sound manager as an example but this holds true for most io systems (graphics, input, physics).
I have read multiple articles about why singletons are bad.
I know it has few uses like logging but what about initalizing and deinitializing.
Are there any problems doing that?
I have a scripting engine that I need to bind on startup to a library.
Libraries don't have main() so what should I use?
Regular functions or a Singleton.
Can this object be copied somehow:
class
{
public:
static void initialize();
static void deinitialize();
} bootstrap;
If not why do people hide the copy ctor, assignment operator and the ctor?
Libraries in C++ have a much simpler way to perform initialization and cleanup. It's the exact same way you'd do it for anything else. RAII.
Wrap everything that needs to be initialized in a class, and perform its initialization in the constructor. Voila, problems solved.
All the usual problems with singletons still apply:
You are going to need more than one instance, even if you hadn't planned for it. If nothing else, you'll want it when unit-testing. Each test should initialize the library from scratch so that it runs in a clean environment. That's hard to do with a singleton approach.
You're screwed as soon as these singletons start referencing each others. Because the actual initialization order isn't visible, you quickly end up with a bunch of circular references resulting in accessing uninitialized singletons or stack overflows or deadlocks or other fun errors which could have been caught at compile-time if you hadn't been obsessed with making everything global.
Multithreading. It's usually a bad idea to force all threads to share the same instance of a class, becaus it forces that class to lock and synchronize everything, which costs a lot of performance, and may lead to deadlocks.
Spaghetti code. You're hiding your code's dependencies every time you use a singleton or a global. It is no longer clear which objects a function depends on, because not all of them are visible as parameters. And because you don't need to add them as parameters, you easily end up adding far more dependencies than necessary. Which is why singletons are almost impossible to remove once you have them.
A singleton's purpose is to have only ONE instance of a certain class in your system.
The C'tor, D'tor and CC'tor are hidden, in order to have a single access point for receiving the only existing instance.
Usually the instance is static (could be allocated on the heap too) and private, and there's a static method (usually called GetInstance) which returns a reference to this instance.
The question you should ask yourself when deciding whether to have a singleton is : Do I really need to enforce having one object of this class?
There's also the inheritance problem - it can make things complicated if you are planning to inherit from a singleton.
Another problem is How to kill a singleton (the web is filled with articles about this issue)
In some cases it's better to have your private data held statically rather than having a singleton, all depends on the domain.
Note though, that if you're multi-threaded, static variables can give you a pain in the XXX...
So you should analyse your problem carefully before deciding on the design pattern you're going to use...
In your case, I don't think you need a singleton because you want the libraries to be initialized at the beginning, but it has nothing to do with enforcing having only one instance of your class. You could just hold a static flag (static bool Initialized) if all you want is to ensure initializing it only once.
Calling a method once is not reason enough to have a singleton.
It's a good practice to provide an interface for your libraries so that multiple modules (or threads) can use them simultaneously. If you really need to run some code when modules are loaded then use singletons to init parts that must be init once.
count the number of singletons in your design, and call this number 's'
count the number of threads in your design, and call this number 't'
now, raise t to the s-th power; this is roughly the number of hairs you are likely to lose while debugging the resulting code.
(I personally have run afoul of code that has over 50 singletons with 10 different threads all racing to get to .getInstance() first)