Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Singleton Vs static methods [duplicate]

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.

like image 731
c0de Avatar asked Nov 28 '10 22:11

c0de


People also ask

Why should you avoid singletons?

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.

Is singleton better than static?

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.

What if I use static instead making singleton?

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.

Is singleton and static same?

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.


2 Answers

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).

like image 75
ChrisW Avatar answered Nov 11 '22 08:11

ChrisW


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.

like image 20
T33C Avatar answered Nov 11 '22 09:11

T33C