When this question has been asked before on StackOverflow in 2011 and 2015, all answers as of now suggest to use a Singleton.
But that’s not right.
Singletons are defined by the Gang of Four to mean two things: 1) Ensure a single instance 2) Accessible everywhere
I do not want accessibility everywhere. There are many posts as to the havoc globally mutable state can cause. My proposed solution is as follows:
public class MyClass
{
private static bool instanceCreated = false;
public static MyClass Create()
{
if (instanceCreated)
{
throw new Exception("Already created one instance of MyClass.");
}
MyClass myClass = new MyClass();
instanceCreated = true;
return myClass;
}
private MyClass()
{
}
}
For context, as per comment: I'm trying to only allow one instance because I thought that was good practice... hence why people use Singleton. I am designing an adapter for my database, and do not want it modified from just anywhere.
My question:
Did I stumble across a new and innovative technique? Or is this well-documented, perhaps even a design pattern or its own? What other resources should I, and future searchers of this question, look at to understand how to ensure single instance of class WITHOUT the singleton pattern?
Create
; how is the author of that program supposed to know that they cannot use both libraries in the same program? Which ever library goes second will always crash, and cannot obtain the instance it needs.