A singleton pattern guarantees that a class has and has only one instance, and provides a global access point to access it. In programming, there are many situations where you have to make sure that a class can have only one instance. From this sentence can be seen, The core of the singleton pattern: how to control any invocation of a user using new to an instance constructor of a class. How do you bypass conventional constructors and provide a mechanism to ensure that a class has only one instance? This should be the responsibility of the Class Designer rather than the user.
First, the single case pattern intention
Ensure that a class has and has only one instance, and provides a global access point to access it.
A UML diagram of a single case pattern (the diagram to http://www.dofactory.com/)
Example explanation single case mode
Take a look at the following simple example:
1namespace Designpattern.singleton
2{
3 public class Singleton
4 {
5//Static private property
6 private static Singleton instance;
7
8///<summary>
9///Private constructor--Let the class's consumer not call this constructor
ten///</summary>
private Single Ton () in the public
static Singleton Instance {
18 if (instance = = null)
{
instance = new Singleton ();
return to instance;//returns always the first instance of the object}
27//test class C27/>28 class Testsingleton
{public
static void Main2 (string[] args) Singl
Eton t1 = singleton.instance;
Singleton t2 = singleton.instance;
Console.WriteLine (object. ReferenceEquals (t1, t2) = = true);
}
37}