Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wonder if there is a mechanism or pattern to allow only one instance of a class in C#. I have heard of the Singleton class, but i don't know how to use it well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
588 views
Welcome To Ask or Share your Answers For Others

1 Answer

Using singleton, that is a class which only allows a single instance of itself to be created.

public sealed class Singleton
{
     public static readonly Singleton instance = new Singleton();
     private Singleton() {}
}

The operation of this pattern is simple and could be reduced to the following:

Hide the constructor of the Singleton class, so that clients may not be instantiated. To declare the Singleton class private member variable containing the reference to the unique instance that we handle. Provide in class Singleton a function or property that provides access to the one maintained by the Singleton instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...