thready
asked on
C# Singleton question
Hi Experts,
I would like to use a Singleton, but, kind of contradictingly, I'd like to use the Singleton sometimes, and also be able to create a new instance of the same class. I have the following code that creates a Singleton. Is there a way to modify this so that I can create a new one?
Thanks!
Mike
I would like to use a Singleton, but, kind of contradictingly, I'd like to use the Singleton sometimes, and also be able to create a new instance of the same class. I have the following code that creates a Singleton. Is there a way to modify this so that I can create a new one?
Thanks!
Mike
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you.
It would appear that you don't need a singleton at all. One, if not the(?), purpose of a singleton is that it's designed such that only a single instance of itself is ever created/used. If you re-initialize the instance, then by definition your object is not a singleton but instead you just have some psuedo-static class that's probably difficult to understand and correctly use.
There are few places where the singleton pattern is the correct one. The most common example is some kind of logging utility that doesn't necessarily impact your program, but instead it just logs output. It doesn't interact with the rest of your code.
Most of the time, when you find yourself thinking, "A singleton will solve this problem!," all you really need is just a static class.
There are few places where the singleton pattern is the correct one. The most common example is some kind of logging utility that doesn't necessarily impact your program, but instead it just logs output. It doesn't interact with the rest of your code.
Most of the time, when you find yourself thinking, "A singleton will solve this problem!," all you really need is just a static class.
The question is - when you need to create new instance?