I have a singleton, and I'm debating whether 开发者_JS百科it would be bad practice to have some static methods that sort of hide the singleton's usage from the client. For example:
Singleton::Instance()->Foo();
Vs.
Singleton::FooHelper();
Where FooHelper is defined:
class Singleton
{
...
static void FooHelper()
{
Singleton::Instance()->Foo();
}
...
}
Is the second solution considered bad practice? I wouldn't be making helper functions for all the methods of Singleton, just the ones that are used very frequently by the client code.
One idea would be to get rid of the singleton altogether. Make it a proper class with a proper owner in your system, which other classes have to go to get hold of that object. Then you can access it like a "normal" object, and it won't look so jarring.
Many folks consider singletons an anti-pattern. The big problem with them I've found is they make it very hard to generalize your code when you find a need for that one day. As computers get faster and get more cores, where I work we now find ourselves wanting the ability to run more than one of our main program on the same machine at once. The biggest challenge to doing this is all the singletons we foolishly coded up.
Try doing without the singleton this once and see how it works out for you.
This is not bad practice as long as 1° the original Foo()
method is still publicly available and 2° the naming scheme makes it obvious that FooHelper()
is equivalent to calling Foo()
on the instance.
Of course, if you find yourself always calling FooHelper()
and never calling Foo()
, reconsider your design: the point of a singleton (as opposed to a plain global-functions-in-namespace approach) is that it's an object — so at least some parts of your code should be using it as such.
精彩评论