Possible Duplicate:
C++ singleton vs completely static object
Hi,
why should I prefer a singleton over static class methods.
MoneyPrinter::addJob(PrinterJob &job);
or
MoneyPrinter::getInstance().addJob(PrinterJob &job);
Is it only a matter of style? What do you use? Why?
ps. I know that sigletons are not 开发者_运维百科threadsafe (first initialization) by default.
why should I prefer a singleton over static class methods
A singleton can have internal state (in your example, the list of added jobs), i.e. the member data of the singleton class.
What do you use? Why?
If there's no state, then a static method because that's simplest.
Otherwise a singleton, preferably static-initialized (instead of just-in-time or run-time initialized).
A singleton gives you control over when the class is instantiated and as DeadMG points out if you want to instantiate it. A static class is less controllable and is instantiated before main is called.
The sequence in which classes is instantiated can sometimes be critical when the singleton depends on some other class or resource which is not avaiable before main is called.
As you mentioned, if you call a singleton from multiple threads you need to ensure that you have used a thread safe singleton. Scott Meyer's (from Effective C++) is not thread safe for example.
Would be harder to refactor out the Singleton-ness simply because of the syntax used if you use static member functions. There's one reason.
The general rule of singletons is, if you have to ask, don't use it. This is true for any globally mutable state.
精彩评论