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.
The most important drawback of the singleton pattern is sacrificing transparency for convenience. Consider the earlier example. Over time, you lose track of the objects that access the user object and, more importantly, the objects that modify its properties.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.
It is not possible to inherit from a static class, while it is possible with singleton pattern if you want to allow it. So, anyone can inherit from a singleton class, override a method and replace the service. It is not possible to write an extension method to a static class while it is possible for a singleton object.
The difference between the Singleton and Static is Singleton Class can have value when Class object instantiated between server and client, such a way if three client want to have a shared data between them Singleton can be used. Static are always just shared and have no instance but multiple references.
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.
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