So Singletons are bad, then what?
programmers.stackexchange.com
programmers.stackexchange.com
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.
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.
You could argue that it's a static vs dynamic typing thing, and I don't know enough to really dispute that, but it seems to me that there's no inherent reason that a static type system can't handle using a different concrete implementation. I think you can do this with Java/C# by doing some library loading trickery, but it'd be inconvenient.
And that's the whole point of all this, isn't it? Automated testing is a convenience that saves you from doing manual testing. Unit testing is a convenience that catches test failures before commit rather than during the automated testing phase. Creating the unit test, well, is it more convenient to create 8 interfaces and completely change the way the code is structured, or is it more convenient to mock out the singleton? It depends on the circumstance, I've done both in various languages. It's good to have the option.
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.
In reply to your original question, its not extremely bad if you can't unit test that class alone , but in this case you wouldn't be able to unit test anything which uses it either.
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.
If you really want to have different cache implementation for testing purpose, use C as just an instance storage, and return reference not to self but to cache interface. Put a switch inside static C.getX() that returns IX. Inside of switch statement see if System.getProperty("isTest")=true and return XSimple (which implements IX), otherwise return XReal (which also implements IX). Few lines of code, transparent and debuggable.
But then I'm not testing the code that uses the cache, I'm testing the cache plus the code that uses the cache. Which is a valuable test but a separate one.
Regarding your proposed implementation, that sounds like basically what I proposed here:
In quite a few codebases I've seen, the amount of tests was entirely unrelated to how stable and maintainable the system was. Some times developers just fixed the tests, rather than the bugs. And in many cases, there were a slew of failing tests even though the system ran fine.
class SomeResource : public Singleton<SomeResource> {
private:
SomeResource *instance
public:
SomeResource &Instance() {
if(!resource) makeResource();
return *resource;
}
void Mock(SomeResource *mock) {
resource = mock
}
}
class MockResource : SomeResource {
...
}a) Now your singleton is also responsible for providing a mock implementation of itself (which shouldn't really be one of its concerns).
b) You didn't really do anything here: the class under test is still going to use the concrete implementation of C. You need a way of providing a mock implementation to your class while testing. The obvious answer to how to do it is dependency injection. But if you're going down that route, you can just ditch the whole singleton thing, instantiate a class using "new" somewhere else and pass it to your class. And in your unit test, you simply pass the mock implementation. This is what DI containers like Spring do. We'd be doing the exact same thing here, only manually.
b) You're touching a tiny part of the implementation of the real C, yes. If you're able to push the Instance and Mock functions into Singleton, you might be touching literally no code of C other than relying on the fact that it in-fact inherits from Singleton.
I nonetheless agree dependency injection is a better solution. The biggest objection I have to this implementation is that there's nothing that tells me I should be mocking C, or catches it when I forget to mock C.
The only reasonable use case I've encountered in practice is the ability to replace some major components of your program with stubs for use in automated testing.
bool isCommentSpam(int id, ICommentCache commentCache) {
return commentCache.getCommentById(id).getScore() > THRESHOLD;
}
bool isCommentSpam(int id) {
return Cache.getCommentCache().getCommentById(id).getScore() > THRESHOLD:
}
In the former, you make the fact that the method uses the comment cache explicit. If you were to have another method that deleted a video (and all its associated comments), it would have to ask for a comment cache explicitly in its signature. This would make the fact that these two methods interact with each other explicit and make reasoning easier.This is perhaps less important than the ease of testing, etc. that you get as well, but I find that I work better with this style.
EDIT: Not to mention, that passing references to cache object along each method call bloats the code. Now you have references to cache not in 50 cases where cache is used (example #2), but in 5000 cases because each method signature needs to include reference to cache (each method along the call hierarchy until you reach the point where you use cache object).
if (isCommentSpam(423)) {
doSomething();
}
if(isCommentSpam(423, commentCache)) {
doSomething();
}
See, the fact that the first kind uses the CommentCache is completely opaque to you when you're reading the code. You don't know it does until you actually look inside `isCommentSpam`. The second way, you can trace the flow of information through the program very easily.It's perfectly feasible to instrument your app at the top-level to pass the needed components down, and then use them through interfaces. Thus, you pay the cost of the interfaces, plus the cognitive cost of using those interfaces, instead of implementation classes. Same effect as DI, but no container.
Aside: there are costs and benefits to a good software architecture, but you won't learn it from reading HN.
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.
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.
The one nice thing it does provide is access to defining extension methods, which aren't allowed outside static classes.
Yeah.
The flip side is that if quality does matter for a project, then unit tests are important, and the whole point of Aaronaught's answer is that things like unit tests and refactoring are usually impossible with a traditional singleton pattern.
It's definitely a fine line though. As a wise programmer once said: "Broken gets fixed, but shitty lasts forever." Be careful when you deliberately choose the shitty route - it usually comes back to bite you.
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/25/root-cause-of-singletons/
http://misko.hevery.com/2008/08/21/where-have-all-the-single...
I miss this guy in Java world.
testCreditCardCharge() {
CreditCardProcessor.init();
CreditCard c = new CreditCard(
"1234 5678 9012 3456", 5, 2008);
c.charge(100);
}
Instead I would expect a singleton to be used this way. Which takes care of initialization where its needed. class CreditCard {
private number;
function charge(amount){
processor = CreditCardProcessor.getInstance();
processor.go(number, amount);
}
}
I'm not saying this is better way to process this datamodel, but it is the correct way to use a singleton. processor = CreditCardProcessor.getInstance();
processor.charge(number, amount);
And this: CreditCardProcessor.charge(number, amount);
The only difference is whether the state of the CreditCardProcessor is stored statically on the class, or is stored in one magical instance. They will both have the exact same pathology in the code and during testing. The former will be slightly easier to refactor, since at least it's already based on instances.I honestly think there's a huge potential difference between
CreditCardProcessor.init()
CreditCardProcessor.charge(number, amount);
and CreditCardProcessor.getInstance().charge(number, amount);To address your points specifically:
1. Whether the item is lazily initialized or not is an implementation detail. In fact, the call of "init" on the first format is lazy initialization; an eager initialization would have completed at class-load.
2. Either method can implement exclusionary locks. There is no difference here.
3. This is the big difference between the two, but you write it as if it's a benefit unto itself. From an API perspective, why do I care whether I'm manipulating an variables that live on an object instance or statically on the class?
Here's an exercise. How would you even know whether the code to a Singleton class looks like this?
class SomeNumber {
private static Integer value;
public static SomeNumber getInstance() {
if (value == null) value = 5;
return new SomeNumber();
}
public Integer getValue() {
return value;
}
}
If you cannot tell whether the Singleton class was implemented this way from the external API, then there is no difference between the two implementations.I've actually been wanting ways of enforcing arbitrary rules on the structure of my code at compile time...
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.
The fact that you said x is always y in programming is troubling. Sure singletons are usually a lazy solution, but saying there isn't a single case EVER where a single is the proper solution is ridiculous.
Is it? Some things are simply mistakes to and through. Consider nailing your penis to a table, is it ever the right solution to anything, aside from "how could I get my penis nailed to a table"?
I have a third-party library that has expensive initialization done inside of its class's parameterless constructor. Once created the library's instance is fully thread safe. Because I only wish to incur the initialization cost once I have a straightforward singleton to wrap the instance:
GetInstance():
hold mutex
if instance is null:
instance = ExpensiveLibraryConstructor()
return instance
Now the code I'm writing code plugs into a framework I don't control. I create a class that conforms to the framework's client interface and the framework creates instances of my class and calls a Run() method. My Run() method needs to be able to make use of the third-party library, so I'm calling my singleton's GetInstance() method there.Not that it would make much practical difference but ExpensiveLibraryConstructor() needs some environment initialization done before it will succeed so I cannot invoke the constructor in global scope.
Do you know of a better way?
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.
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.
Maybe not so in all languages?
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.
And not surprisingly singletons are being abused just like good 'ol global variables by bad programmers, and thus eventually they will be considered bad. And then a new way of handling some global state will be invented because singletons are bad and we still need some way of accessing some global state in some cases.
And so the cycle continues.
Namely: "Where on earth is this set to X, it should be Y at this point!"
Singletons aren't bad, they're just misused a lot by bad programmers. It's like saying "Food is bad," and sure, people misuse food and hurt themselves, but that doesn't mean we should ban food.
And then the problem magically disappears, but only when you trace it.
You get into serious trouble with "lock free" stuff, where pretty much any additional activity (even register operations) will perturb things and make bugs go away. Hopefully at this point you have help from the hardware. Then again, if you're doing LF, you're in a special place and probably have the chops to deal with it...
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.
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.
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.appIt's not nitpicking, half of the singleton's purpose is to only ever have a single instance.
† 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.
In my experience, a large bunch of iOS developers tend to use singletons out of imitation. The "sharedWhatever" is the usual way for the framework to provide access to anything that is purposefuly single-instance[1]. Same thing with delegation, though that one is usually less cringe-worthy in practice.
[1] The "the accelerometer on your phone" kind of single-instance, which is a much more defensible use-case than what the typical iOS coder uses them for.
Static variables and methods? Pass the instance down to all children?
I dislike singletons, but will gladly make a static method + static var from time to time.
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
[2]: https://github.com/sdegutis/bahamut/blob/master/Bahamut/SDMu...
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.
http://www.hollance.com/2012/02/dont-abuse-the-app-delegate/
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.
The downside is that you're forcing a new dependency on the user of your API, and that dependency may be an implementation detail that the user should not be concerned with.
You could argue that the user was already depending on that singleton because singletons are effectively globals. But that's not necessarily true as the singleton could have package/module visibility.
I'm not convinced that all encapsulation should be sacrificed on the altar of TDD.
I first ran into the pain of singletons when using them in a framework. This framework formed the bases for small modules, which when loaded together into the same application domain blew up.
My solution was to use IOC/DI. I could still have singletons , but they are just instanced managed by the container. This mean I am not relying on static values for state, which in my view is as bad as global variables.
I guess this is really the problem most people associate with the singleton model, not that there is a single instance in your application, but that typically people use static variables to store the instance.
No, I just refactor my code to not use a singleton anymore. This only involves deleting the static accessor, adding a few properties, and passing a value downward. It would take all of 5 minutes. I don't see any value in designing my architecture around a feature I might never add.
People make the same arguments about using interfaces (think Java not Objective-C ones), they are only useful when you need them, but almost all of the time it's easier to do it in advance than at a later date.
At the end of the day it's your call as the architect of your application. If you can convince yourself using a singleton is a better fit that another method go for it, chances are you'll know your application better than a one of the GOF.
If it then trips you up down the line, you learn from it and revise your thinking the next time you face this problem.
[1]: I'm aware of third party solutions like Kiwi and Cedar, but I haven't found them to make this process much more pleasant than the built-in tools. Apple is really just an overbearing mom in this case, forcing you to use the sweater she chooses, and making life difficult if you don't.
But conversely, if the behavior you are putting in your singleton actually has effects, and can be deemed a dependency on the code that uses it, then it makes sense to make that blatant by passing the reference into each of the dependent modules, if only for unit testing, clarity and mockability.
Video: http://www.youtube.com/watch?v=qKXt9fBDVoY
Slides: http://www.gostevehoward.com/presentations/20131212-moving-t...
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?
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.)
Personally, the added cruft of passing services to every constructor made me want to rip my eyes out.
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.
Don't underestimate the value of machine-checked documentation.
Of course, one also shouldn't underestimate the value of reducing cruft, but you don't seem to be in danger of doing so.
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.
Singleton exists as a pattern to enforce a single instance because of state and side effects. What you're talking about is just a cached instance.
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.
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.
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
Make it easy to use the default one, but also make it easy to swap it out and use a different 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.
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)
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.
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.
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.
It's not usually good to over-engineer or over-spec, but I'd rather have a little bit of that than a whole lot of software that can never scale.
That's true, but there are so many cases were a singleton is way more convenient than the alternatives, and not using it because it might "potentially" need to scale but never does sounds a bit silly to me.
I am agreed though that you must be clear on the specifications, if a shadow of doubt appears is very to play it safe.
@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.
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.
What is being debated here is when a class intentionally restricts how many instances of itself can be instantiated. That is the true "Singleton pattern" - a class that combines two concerns, 1) the behavior of the class and 2) the instantiation pattern of the class.
This isn't a singleton, but a single instance of a object.
You can change the lifetime of an object, by changing a setting in the IoC container. From ApplicationLifetime To SessionLifetime quite easily. That solves the biggest problem of the singleton, which if you ever DO need more than one, it requires a refactoring.
I hate singletons, and I'm a iOS developer. So i'm continually mad about misuse of singletons(Working on legacy code).
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.
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.
That is weird... wouldn't you just do yyy::getInstance() directly? The whole point of singletons is being global right?
Like:
#define GAMELAYERINSTANCE _dir->Instance()->getGameScene()->Instance()->getGameLayerObject()->Instance()
object->getInstance() makes no sense, you already have the object!
So class _dir contains object as a member variable.
_dir->Instance(), already has access to object without doing _dir_Instance()->object->Instance() as an example...?
If getInstance returns an instance of object class, and object is an instance itself, then it doesn't make sense or it is not a singleton.
You can think it like this: if object class has one unique instance, then object == object->getInstance(), so in your case either object != object->getInstance and they are from the same class (hence it is not a singleton) or they are from different classes (once again then, it is not a singleton).
- 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).
[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.
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.
In that sentence, only the class is being initialized, so there's nothing to track. What did you mean? "Instantiate", not "initialize" ?
if (Instance != this) return;