
So Singletons are bad, then what? - tcgv
http://programmers.stackexchange.com/questions/40373/so-singletons-are-bad-then-what
======
shitgoose
Hilarious! Doing x=C.getX() is bad, but if it is hidden by numerous layers of
libraries and monstrous config files, somehow it becomes acceptable. Out of
site, out of mind. The fact that global scope bean is essentially a singleton,
doesn't seem to bother architecturally inclined crowd - they are too busy
admiring sound of their own voice pronouncing words "dependency injection",
"mutability" and "coupling".

The top answer is a perfect example of what is wrong with IT today. It takes a
working solution, declares it wrong and starts piling up classes and
interfaces to solve a problem, that was never a problem in first place (OP
never said that their singleton-based cache didn't work, he merely asked if
there are "better" ways of doing it). So in the end we have the same singleton
cache, but hidden behind interfaces ("It makes the code easier to read" \-
yea, right, easier, my ass! Ctrl+click on interface method and try to read the
code), thousand lines xml Spring configs, and other crap that is completely
irrelevant, hard to follow and debug, but glamorous enough for SOA boys to
spend endless hours talking about it.

~~~
Sandman
Doing x=C.get(x) is bad because there's no way of mocking C, thereby making
unit testing a component that uses C impossible (the unit test will need to
use the concrete implementation of C). Using dependency injection as described
in the accepted answer, and particularly separating the concerns of C by using
several different interfaces allows you to not only mock C, but actually
create mock classes each of which is mocking one particular logical subset of
C's functionalities.

It's easy to dismiss all this as "bloated" and "enterprisey" and people that
use this as "architecture astronauts" but in reality, this pattern really does
help. Well, at least if you want to be able to unit test your code properly.
Otherwise, you might as well just use a singleton object.

~~~
shitgoose
Who says that you have to be able to mock C? Not every class should be
mockable. In case described by OP, why would we want to mock cache anyways? In
most cases singleton is used as a global state that can be easily accessed
from all parts of the app without explicitly passing the state obj. We are
dismissing a useful technique (singleton) based on requirement, that is not
applicable to this technique.

~~~
Sandman
> Who says that you have to be able to mock C? Not every class should be
> mockable. In case described by OP, why would we want to mock cache anyways?

Well it isn't really a unit test if you don't, is it? If you don't mock it
then you're not only testing classes under unit tests, but also C's methods.
And you're doing that not just in one place but in several different places in
your testbase. The same methods. Over and over again.

~~~
shitgoose
I don't understand. If my unit test calls C.getX() over and over again, how is
it bad?

~~~
Sandman
C.getX() is going to be called by many different methods in many classes. This
means that each time you unit test any of these methods, you're also testing
C.getX() when you should only be testing what the method does.

~~~
shitgoose
\+ sign and - sign are also called by unit tests many times, so you also
repeatedly testing arithmetic operations "each time you unit test any of these
methods, ... when you should only be testing what the method does".

Edit: I see what you say, but I think that effort we spend on decomposing app
into perfectly isolated unit tests is far greater then the effort of
identifying and troubleshooting where the less perfect test failed.

------
Pxtl
I always get cranky about people fixating on the difference between a static
class and a singleton. A static class is just your language's default
implementation of the singleton pattern, it just fails at providing any
polymorphism to swap out the object for a new one. Mechanically, they do the
same thing. Single global point of access to some effectively-global-state.

Also, the singleton thing (and interfaces everywhere) stinks of YAGNI. Your
toolkit can find all references to X.Y, which means you can replace all
references to X with a reference to X.Instance.Y. _when_ you need to change a
static class to a singleton, do so.

Or just use a dynamic language where there isn't any difference. Seriously, I
wish C# offered a "root" static class or global variables or something
equivalent so that the singleton pattern was less verbose to implement,
because you _will_ need them.

~~~
arethuza
What other languages than C# have the concept of a static class?

~~~
Pxtl
Other languages can sport a class full of static methods and a private stub
constructor, all C# offers is the means to _force_ a class to only contain
static methods and block the constructor.

You can make an all-static class in _any_ OOP language that supports class-
level methods and members.

That's my point. This argument is all semantics. There's a million little ways
to create something with the functional utility of a Singleton, and there's no
sense in pretending that they're vastly different.

~~~
arethuza
It was just idle curiosity - I wasn't familiar with the term "static class",
looked it up and wondered if that particular set of features (and the term)
were used in any other languages.

~~~
Guvante
Nothing special about it, it was just a cheap feature to add (static was
already reserved and not previously added before class) while helping to
exemplify a common protocol.

The one nice thing it does provide is access to defining extension methods,
which aren't allowed outside static classes.

------
lazydon
Singletons are always a lazy solution to the problem. For me the rule of thumb
is if there's some class requiring lots of work to test, I've been lazy. So,
go back and review my sloppiness.

The questioner was in a way implementing a poor man's cache using Singletons
(I wonder how was he planning to test it); some use it for connection pooling
instead of a specific library.

I've heard even GoF regretted including Singletons in the s/w patterns club.

I'm a big fan of Misko Hevery's (now working on Angular) work on this.

[http://misko.hevery.com/2008/08/17/singletons-are-
pathologic...](http://misko.hevery.com/2008/08/17/singletons-are-pathological-
liars/)

[http://misko.hevery.com/2008/08/25/root-cause-of-
singletons/](http://misko.hevery.com/2008/08/25/root-cause-of-singletons/)

[http://misko.hevery.com/2008/08/21/where-have-all-the-
single...](http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-
gone/)

I miss this guy in Java world.

~~~
pmelendez
>"For me the rule of thumb is if there's some class requiring lots of work to
test, I've been lazy."

Unit tests are great, but when they get in the way I always look it as a
chicken and egg paradox. Is my simple and easy to maintain code inferior
because it is not test friendly? Or is the test friendly alternative inferior
because is more complex and harder to maintain?

And this haven't happened to me just with singletons, sometimes unit tests
just like to get in your way.

~~~
jdmichal
I find the biggest barrier to unit tests is not noticing when it's more
appropriate to create a public static function (probably on another class)
instead of a private one. If a private method is so complex that you cannot
appropriately test it using the public interface, then it really needs to be
its own entity.

------
eludwig
Religious wars against particular design patterns just seem so, well,
religious!

To me, a singleton is a particular implementation of a global variable.
Nothing more. You use it one when you need one. It isn't magic or evil. It's a
global variable.

The problem comes in when you are using one but don't know it. It's the
beginner Spring problem. Developers don't realize that some libraries use them
by default and start storing state there. Needless to say, not good.

~~~
fhd2
> To me, a singleton is a particular implementation of a global variable.

Except that it's not. Global variables aren't initialised lazily, and their
type can be an interface just fine. I can think of a few valid use cases for
singletons, but it's not a great replacement for global variables IMO. Service
locators are closer, and I think they have far more valid use cases than
singletons.

~~~
masklinn
> Except that it's not. Global variables aren't initialised lazily

Depends on the language, and the global.

In java, a static attribute is initialised when the class is first _used_.
Until the class itself is accessed and used, the attribute remains
uninitialized.

In clojure, delay[0] will invoke (and cache) its body the first time it's
deref'd.

[0]
[http://clojuredocs.org/clojure_core/clojure.core/delay](http://clojuredocs.org/clojure_core/clojure.core/delay)

------
csmithuk
Singletons are fine. It's just some idiots plug everything into them then
realise they've blow their toes off with a monolithic ball of mud
architecture.

I use a singleton on _every_ project which is OO based but it only ever holds
the service locator/container.

Asp.net MVC is a fine real world example of how to fuck up Singletons (routing
dictionary, global action filters etc). Totally stinks and is coupled like
glue.

~~~
mattgreenrocks
> I use a singleton on every project which is OO based but it only ever holds
> the service locator/container.

iOS devs _love_ singletons; it seems like almost everything is a
sharedSomething. Definitely a design smell.

Infrastructure can sometimes call for a singleton. It's very convenient to
have something that is only created when it is needed. That way, users only
pay for what they use, and they don't have to bear the conceptual burden of
toting an extra context object around.

But it is a sledgehammer, and the people most inclined to abuse it lack the
ability to tell the damage it is doing to the design.

~~~
frou_dh
It's mildly interesting to note that in practice essentially every GUI
application on OS X is a singleton because the OS makes a strong distinction
between application instances and windows (compared to e.g. MS Windows where
the distinction is muddy).

Launch TextEdit.app twice and there is still only one running instance of the
application. If you want a second window, you open a second window.

    
    
        # instance trivia:
        $ open -n /path/to.app

~~~
masklinn
That's not being a singleton since you _can_ have a second instance if you ask
for it.

~~~
frou_dh
Odd that the pair of you are nitpicking since I both said "in practice" and
gave a command that could be used to produce that screenshot.

~~~
masklinn
> Odd that the pair of you are nitpicking

It's not nitpicking, half of the singleton's purpose is to _only ever_ have a
single instance.

~~~
frou_dh
You're still not telling me anything I don't know.

~~~
masklinn
If you knew it was wrong in the first place, why post it?

~~~
frou_dh
I now realise I was providing reading comprehension training†

† NOT, I REPEAT NOT, a literal course of training. I want to make it doubly
clear that I did not certify anyone and can not be held responsible for any of
their future actions vis-a-vis reading or comprehending.

------
sdegutis
Singletons aren't always bad. I use a few in my Objective-C Cocoa apps to
share common behavior. For example in my music player Bahamut[1], I have a
singleton for actually playing music. This way, you can have several Bahamut
windows open at a time which all control the same music player.

Sure, you could store this variable as a property on AppDelegate or some other
parent in the object graph, and then either pass it down to each window
controller which needs it, or give them access to it, either directly or via
delegates or something. But these are all very convoluted compared to having a
single class-method in the class itself which returns a shared (static)
object.

The only caveat is to make sure that you don't introduce race conditions by
poor design. For example, don't do stuff in -init on your singleton, and
especially don't do stuff that might call other stuff that might access the
singleton via the public accessor. Doing so could turn into an infinite loop
if -init is called when creating the singleton. (I've done this before.)
Instead, just add a new -setup method and call that somewhere in
-applicationDidFinishLaunching: or whatever. It's also a good idea to use
dispatch_once to create the singleton[2].

EDIT: Of course, these suggestions don't only apply to Objective-C apps,
although your entry points and race-condition-avoiding functions will
certainly be different in other environments.

[1]:
[https://github.com/sdegutis/bahamut](https://github.com/sdegutis/bahamut)

[2]:
[https://github.com/sdegutis/bahamut/blob/master/Bahamut/SDMu...](https://github.com/sdegutis/bahamut/blob/master/Bahamut/SDMusicPlayer.m#L44-L51)

~~~
jarrett
> But these are all very convoluted compared to having a single class-method
> in the class itself which returns a shared (static) object.

I used to think the same thing. But lately, I've come to think it's better for
code to explicitly reveal its dependencies via its public API. If class Foo
uses the singleton class Bar, you can't see that dependency just by looking at
Foo's API.

My preferred solution in OOP is either: a) have Foo's constructor accept a
reference to an instance of Bar, or b) for any method on Foo that requires a
Bar, have that method accept a reference to an instance of Bar. I find this
disciplined approach helps me reason about my code and understand how units of
code relate to each other.

I only developed this insight after diving into functional programming. Prior
to that, I was all about convenience. Singletons were convenient, and I didn't
want to pass a references around all the time. It seemed like a lot of
pointless ceremony. Now I've changed my tune. Rather than pointless ceremony,
it's a form of self-documentation.

~~~
sdegutis
What's the benefit of doing it that way? The only one you mentioned is self-
documentation, but that seems like a weak argument against these kind of
singletons. It sounds like you're giving up the convenience of singletons
solely for the sake of not having singletons, which seems pointless in itself.

~~~
jarrett
I'm giving up singletons because hidden dependencies are a source of bugs. Let
me make it more concrete:

Suppose classes A, B, and C use singleton class S, and S has state. Via the
hidden dependency on S, it's possible for A, B, and C to affect each other
_without explicitly calling each other 's methods._

As a programmer, you can take those hidden interactions into account and still
have a relatively bug-free program. But it's one more thing you have to hold
in your head. When you return to the project six months later, you have to
read through the internal code of A, B, and C to see these interactions; the
public APIs don't reveal them. You spend more time figuring out how the
objects interact, and there's a greater chance you'll fail to notice an
interaction.

~~~
sdegutis
In the general case, I agree. But for a very few things, singletons make fine
sense. Usually in small programs where you can draw the entire object graph on
a single piece of paper, and where all the features it will have are known up
front.

~~~
jarrett
Certainly! Tiny programs are the exception to most best practices. (Not
security best practices, but I digress.) I write a lot of little programs, and
they're certainly not all works of art. Sometimes you need to bang out a tiny
program quickly, and it's never going to become a maintenance burden. In which
case you can use any pattern or anti-pattern you like.

~~~
sdegutis
That sounds like a very black/white way to say it. I don't agree that using a
singleton in small programs is an anti-pattern. The world is much more gray
than that.

~~~
jarrett
I said you can use anti-patterns in small programs, not that singleton is an
example of an anti-pattern. I don't believe singleton is so terrible as to be
an anti-pattern, even for big programs. I just think it has some downsides
that are really worth considering before you use it.

------
martian
A great talk on the topic is this one. The basic argument is that global
singletons (and global state generally) is detrimental to maintainability,
flexibility, and testability. The talk discusses several strategies for moving
away from global-state to a dependency-injected and testable codebase.

Video:
[http://www.youtube.com/watch?v=qKXt9fBDVoY](http://www.youtube.com/watch?v=qKXt9fBDVoY)

Slides:
[http://www.gostevehoward.com/presentations/20131212-moving-t...](http://www.gostevehoward.com/presentations/20131212-moving-
to-wyoming/)

~~~
goostavos
Ah, I really enjoyed that talk. Thanks for the link!

I've been trying to move into more of a DI style with my code so that it's
easier to test. One thing that I'm fuzzy on is _where_ you instantiate
everything.

In the past, if I have something like a UserSettings kind of structure, I
would usually turn it into a singleton. It made it conceptually simply to
instantiate it at the start of the program, and then have any other class that
needed it to simply do a `user_settings.get_instance()` type of call.

If going a DI route, would the UserSettings object be instantied in the
program's start, and then simply passed as a parameter to every object that
needs it? I tried it out, but it felt a little "off" passing this one object
to almost every class that had anything to do with user settings. Is that just
what you do when your doing DI?

------
fhd2
I've been using manual DI a lot (there aren't many reasonable alternatives in
C++), and occasionally ran into situations where doing that was insanely
cumbersome. Like passing a resource managers down a widget hierarchy. Service
locators implemented as singletons have served me well in those cases. They're
fairly simple, and share almost all the benefits of DI (as opposed to
singletons).

Some people have been calling service locators an "anti-pattern" as well, but
I'm not buying it. Singletons have very obvious drawbacks and have been
incredibly overused, so they sort of deserve that term - even if they have a
few valid uses. Service locators on the other hand have very few drawbacks,
the only real one I can think of is that dependencies are no longer obvious.
Is that really that much worse than throwing complex IoC containers into the
mix? (Note that I just recommend service locators as a fallback when manual DI
doesn't make sense. I much prefer manual DI generally.)

~~~
mikegioia
I've spent the last few months (casually) testing the differences between the
service container and DI container and I've come to the conclusion that it's a
stylistic decision. I found that using a DIC and passing references to
services to the constructor of every class was just far too cumbersome. Is it
clear which services the class uses? Absolutely. But it's also clear if you
document the services used before the class declaration. The cited advantage
of DI is that it's easier to pass service mocks during testing. This isn't
difficult to do with a service locator; as long as you instantiate your
services at the beginning of the test you can have full control over mocking
certain services on a test-by-test, or group-by-group level.

Personally, the added cruft of passing services to every constructor made me
want to rip my eyes out.

~~~
Glide
I am of the school of thought that making relationships explicit leads to
better coding practices and use DI via constructor to do so.

I think the really important factor though is how mature the ecosystem is in
supporting DI. The richness of C# and Java DI container implementations make
using service locator patterns dubious. Well and how many ice cold stares you
would get by using service locators. I'm trying my hand at iOS development
after years of C# and the ecosystem is radically different.

On the other hand mocking libraries are a dream in a message passing runtime
like Objective-C.

------
mnw21cam
Not all singletons are "global state".

Yes, I agree that using singletons to store global state is a bit dumb. You
may as well use static methods and variables.

Where a singleton does become useful is as an immutable carrier of methods. No
state.

It means that an object somewhere can have a reference to a WeirdOperator
object, which contains a method called doWeirdOperation(inputs). WeirdOperator
would then be an interface or abstract class, and various different operators
are implementations, thus effectively allowing methods to be passed around.
Consider Comparator (in Java).

The alternative is to access methods by introspection, but doing
Method.invoke(parameters) is nasty and evil and slightly slower than doing it
properly.

~~~
masklinn
> Not all singletons are "global state".

Then why have a singleton?

> Where a singleton does become useful is as an immutable carrier of methods.
> No state.

Why have a singleton? Just use functions, or static/class methods in KON
languages.

~~~
mnw21cam
Certain languages don't have methods as first class objects which can be
passed around. In Java, you can pass around a Method object, but it isn't
really the full thing, as calling it is not type safe, and is slower than a
real method call. Likewise, passing around a Class object in order to identify
a static method to use is equally unwieldy.

Therefore, a singleton object can be passed around, and it carries with it the
implementation of the method. That allows you to have a variable that
effectively references a type-safe fast method, allowing the nearest thing to
having methods as first class objects.

~~~
masklinn
1\. so you're not only using singletons but you're using them in horrible
ways, that's just great

2\. to pass your singleton around, you need to know its type. If you know its
type, you can just bolt the methods on the type itself and get rid of the
useless singleton

~~~
mnw21cam
No, you don't need to know the singleton's type. You can have several
implementations of an interface, each of which is a singleton. Then you have a
reference to the interface type, which allows different methods to be
selected.

~~~
masklinn
Ah yes, the fabled multisingleton, because once you've dug your hole there's
nothing better than filling it with raw sewage, and once you've got a
singleton you can fill it up with half a dozen interfaces because reasons.

------
herge
The big issue with singleton is that every time you have one db connection,
one cache store, one file store, one of anything, you wind up needing a second
one.

Make it easy to use the default one, but also make it easy to swap it out and
use a different one.

~~~
pmelendez
>" you wind up needing a second one"

And by that moment it is not a singleton any more. The other way around is
also true, you design your system to be scalable in db, cache store, etc. and
you end using only one.

~~~
masklinn
> And by that moment it is not a singleton any more.

That's the point. If it's originally a singleton and you need a second
instance, you're going to have a hard time. If it's a regular factory/object
and you only ever use a single instance, chances are nothing will care (much,
it may let some concurrency bugs or global state creep in)

~~~
pmelendez
>". If it's a regular factory/object and you only ever use a single instance,
chances are nothing will care"

That's true, although if it is a single instance but not global then you are
not enjoying the benefits of the guaranteed of an unique instance.

A well used singleton is a great tool that simplify things a lot.

~~~
masklinn
> A well used singleton

Something which I've come to believe does not exist, the pattern itself is
broken. Thus,

> singleton is a great tool

no.

> that simplify things a lot.

Paraphrasing Mencken, for every complex problem there is an answer that is
clear, simple, and wrong. Singleton is ever that answer.

~~~
pmelendez
>Something which I've come to believe does not exist, the pattern itself is
broken. >Paraphrasing Mencken, for every complex problem there is an answer
that is clear, simple, and wrong. Singleton is ever that answer.

Just because you haven't found a good use it doesn't mean it doesn't exist.
And about Mencken... All he said is that you can't have Singletons without
having a Global State (obvious) and apparently he has an strong allergy to
global states.

Global states are fine. Sure, they will make your tests harder but there are a
lot of software that don't use unit test for legitimate reasons and hence
don't have that problem.

------
JulianMorrison
Static classes and singletons just tell you that the people who shoehorned
everything into an OOP paradigm in your language of choice were mistaken,
because there are plenty of things that are simpler and clearer as top level
functions and data.

~~~
mikegioia
I think you're right, but wouldn't the alternative then just be namespacing
all of your top level functions into separate files? It seems that a static
class of related functions is just another way to organize top level
functions.

------
msluyter
Having used Spring for a year or so now, I'm curious what people think of
singletons in Spring? Most of the problems noted in the OP (inability to use
interfaces, unable to mock, tight coupling, etc...) aren't really problems
that I've noticed. For example, if you're autowiring a typical spring bean, as
in:

    
    
        @Autowired
        private Blah blah;
    

You can actually autowire an interface here. Similarly, it's pretty easy to
mock these or swap them out in tests. Parallelization is usually handled by
not storing private state in a singleton bean.

I'm no Spring expert, so I'm not sure what I may be missing, but most of these
concerns appear to be less problematic than many suggest.[1]

[1] Nothing is perfect, of course. I have noticed problems with spring
singletons where a test would basically screw up the application context,
causing subsequent tests to fail. This caused some hair pulling until I
learned about @DirtiesContext.

~~~
masklinn
That's not a singleton, that's just injecting the same instance everywhere.

~~~
taeric
How is that not a singleton? I can see the argument that dependency injection
is better than a factory method. Especially considering the memory model, but
I thought this was still a singleton.

~~~
masklinn
> How is that not a singleton?

The way it is normally used, a singleton is a self-managing, globally
accessible, single-instanced object (lazy or not). Just having a single
instance does not a singleton make.

~~~
taeric
So the complaint is against the implementation detail of a singleton? Because,
just having a single instance is the crux of the benefit for that pattern.

------
mercurial
Then what? Then you use dependency injection if you think you need a
singleton, and inject a single instance of a cache object. Which means you can
mock it when unit testing, or make different instances of it if needed, or
have different implementations of it.

------
fleitz
In theory there is absolutely nothing wrong with singletons.

In practice singletons become God objects where hack upon hack upon hack is
placed.

Eventually to modify a program in a safe way you end up needing to understand
the entire program because everything depends on the singleton and the
singleton depends on everything else.

Singletons like writing an entire program using only global vars are a
tradeoff, you tradeoff maintainability and design for performance and ease of
(initial) implementation.

In the long term maintainability is usually more important than performance
and ease of initial implementation.

------
jason_slack
Without starting a flame war, I use a few singletons in my game and I dont
understand why it is a problem.

The instantiation of the game, an object that manages layers, HUDS,
Preferences and saving game data (it is done in a separate thread).

I have also worked places where literally every class is a singleton
(practically, not really all) and to avoid the
xxx->getInstance()->yyy->getInstance()...... They would use some Defines to
shorten typing it all.

~~~
mattfenwick
The major problem they cause IMHO is coupling. Some examples of how this has
bitten me:

\- can't instantiate the singleton differently.

\- program does task A, then task B, and both use the singleton; now you have
to worry about the state that the singleton was left in after completing task
A.

\- can't create multiple, separate instances.

\- can't easily mock for testing.

\- can't easily swap out with a different implementation.

I've run into each of these problems, and I can never see any value provided
by the singleton. All the pattern does is reduce the flexibility,
adaptability, and usefulness of the code it's applied to (at least in my
experience -- I'm not implying that it's always or necessarily so).

~~~
jason_slack
I definitely agree that there are places where a singleton just is in no way
the correct option. You have laid out some good examples here.

------
StevePerkins
Reading and re-reading the StackExchange answer with the most votes, I'm still
not sure I get it. It SEEMS like he's saying:

[1] Hand-rolling a class around the "Gang of Four" singleton pattern is bad
(i.e. tightly coupled, etc).

[2] Grabbing a singleton reference from Spring, CDI, Guice, or some other
dependency injection framework is awesome (i.e. easier to use inheritance,
abstract out some interfaces, inject mock objects into your unit tests, etc).

Am I missing something here, or is this entire discussion really no more
complex than that (once you scrape away the enterprise-babble)? It's been
almost a decade since I last worked on a non-trivial project that wasn't using
a dependency-injection framework anyway, so some of this may just be so
obvious I haven't thought about it in awhile.

~~~
jdmichal
The top answer is basically saying:

1\. The "Gang of Four" "Singleton" pattern, meaning stateful functionality
that is statically available from anywhere, is broken. It hides dependencies
and makes it impossible to uncouple the items for testing.

2\. However, the idea of an application needing a single instance of an
object, whether it be a configuration or renderer or what-have-you, is quite
common.

3\. Using "dependency injection" allows use of single instances, without the
"Singleton" pattern. Which, to clarify, does not necessarily mean the more
magical forms of dependency injection found in systems such as Spring, where
you simply declare a variable and it is magically fulfilled later. It can also
just be a parameter in the constructor of the dependent object.

------
jimmaswell
Here's a good use of something close to a singleton. Different things will
initialize the class, and you want to keep track of the last one initialized,
so that's what you assign to the static T Instance. I used this for a
component that could be added to something, but the Update function of which
should only run for the latest initialization.

~~~
gohrt
> Different things will initialize the class, and you want to keep track of
> the last one initialized,

In that sentence, only the class is being initialized, so there's nothing to
track. What did you mean? "Instantiate", not "initialize" ?

~~~
jimmaswell
yes, Instantiate. the class's Update had

if (Instance != this) return;

------
jimmaswell
There's nothing wrong with singletons when they're used when needed. They've
been particularly useful in the Unity/C# development I've done on an MMO, both
on the client and server. The problems someone listed in an answer haven't
really occurred in our use as far as I know.

------
jokoon
I've got to understand how a singleton is better than a global variable

------
yawz
Some of the singleton addiction comes from premature optimization.

~~~
camus2
or the lack of IoC containers.

