I use singletons a lot because I hate to pass an object of the main class to member classes in order to allow them to access the main class.
Class Foo
{
A* a;
B* b;
C* c;
};
For example in the above example if A,B and C would like to access Foo- I would have to pass the object of Foo each one of them, and store it as their member variable (or give the object in every function call). This works, but it does not feel right and requires more code writing.
Instead, I can make Foo a singleton (of course only if there can be only 1 instance) and then just call Foo::getInstance()->… from A, B and C. And I do not have to pass any objects. I find this very handy.
Now, the problem is that I have a situation where there can be multiple instances of Foo. Obviously I cannot use singleton pattern. But I do not want to pass variables nor store them in member classes. Too much code! 🙂
As an example,
I hate this:
A::A(Foo* foo) : m_foo(foo)
{
}
and this:
void A::someFunc(Foo* foo, int someParam)
{
}
But, I love this:
A::A()
{
}
void A::someFunc(int someParam)
{
Foo* foo = Foo::getInstance();
}
Is there any other way to do it? Something that resembles the singleton pattern?
This kind of pattern is creating a bunch of circular references, which in general is a code smell. You may want to take a solid look at your design, because the usual way to solve these sort of relationship problems is to create a third class that interacts with both existing classes. Alternately, what wrong with passing along a reference to the containing class if you really need that behavior?