views:

191

answers:

2

Guys,

I have a question, is this the correct approach to make a Generic Singleton?

 public class Singleton<T> where T : class, new()
    {
        private static T instance = null;

        private Singleton() { }

        public static T Instancia
        {
            get 
            {
                if (instance == null)
                    instance = new T();
                return instance;
            }
        }
    }

Thanks in advanced.

EDIT:

Checking some PDFs I found a generic Singleton made this other way, is this other correct?

public class Singleton<T> where T : class, new()
{
    Singleton() { }

    class SingletonCreator
    {
        static SingletonCreator() { }
        // Private object instantiated with private constructor
        internal static readonly T instance = new T();
    }

    public static T UniqueInstance
    {
        get { return SingletonCreator.instance; }
    }
}

Thanks!!!

+6  A: 

The problem with a generic singleton factory is that since it is generic you do not control the "singleton" type that is instantiated so you can never guarantee that the instance you create will be the only instance in the application.

If a user can provide a type to as a generic type argument then they can also create instances of that type. In other words, you cannot create a generic singleton factory - it undermines the pattern itself.

Andrew Hare
Could the type be saved in a static array, though?
Franz
@Franz - I am not sure what you mean - could you ask your question in a different way?
Andrew Hare
Well you can make the constructors protected and make the template class a friend. Then only the Singleton-class can make instances.Oops, I do not know if friends exists in C#, was thinking of C++.
monoceres
Is is true that the type to be made a singleton could have an internal constructor but that would only guarantee that the type was a singleton *outside the current assembly*. You cannot create a true singleton this way as other types in the same assembly could create instances of the singleton type just as easily.
Andrew Hare
Andrew thank you very much for your reply. Is the second version accurate? Do you find any problem with that, I took it from Judith Bishop´s Design Patterns in C# book.
MRFerocius
While you can't restrict how many times Singleton<T> is used, it is certainly still going to work as a base implementation to allow singletons of various differing types. I don't think this answer necessarily considers all use-cases. For example, Singleton<MyClassA> will be a valid singleton type.
Jeff Yates
Andrew, what I meant is having an static array of types that have already been instantiated in the generic class, which is then checked against the type of the current class. I don't know whether this is possible in C# though, since I come more from a scripting-language background, where this would be easily possible (PHP, y'know?)
Franz
'singleton factory' sounds similar as 'unique number duplicator' for me...
Regent
+1  A: 

For a generic piece of code that will be reused, you should consider thread safety at the point where you create the singleton instance.

As it is, (instance == null) could evaluate to true on separate threads.

frou
Good point, though realistically, there are many constructs which are not thread safe, including most collections which we use on a daily basis.
Nick
@Nick: Advocating bad behaviour because there exists bad behaviour is very very poor.
Jeff Yates
@Jeff - I don't think it's advocating bad behavior at all. Most applications don't need to be thread safe, so it's not always worth the cycles to ensure that it is without that requirement. It's subjective. Saying that a solution is bad because it doesn't account for a use that most people won't have isn't necessarily valid.
Nick
@Nick "not worth the cycles" sounds like premature optimisation to me. When thread safety is as easy to add as it is in this case, a small piece of generic code, why not?
frou
@Nick: I was commenting more on the philosophy that existing bad behaviour allows others to repeat behaviour than the advice for this particular question.
Jeff Yates
@Jeff - I understand, but it also implies that non-thread safe collections are a bad behavior, since that is what I mentioned specifically, and I really don't think they are. But as we've seen, it brings up all sorts of others with premature optimization and over architecture, etc.
Nick