A few days ago, I studied the QQ project in a three-tier model. after doing a good job, I found that the writing was messy, mainly because there were too many static variables between forms. I was a bit touched when I saw an example from another blog:
Implementation of Singleton Mode
The Singleton mode is implemented based on two main points:
1) do not directly use the class constructor, but also provide a public static method to construct the class instance. Generally, this method is named instance. Public ensures its global visibility, and static methods ensure that no extra instances are created.
2) set the class constructor to private, that is, to hide the constructor. Any method that attempts to create an instance using the constructor will report an error. This prevents developers from directly creating class instances by bypassing the above instance method.
You can use the above two points to completely control the creation of the class: no matter how many places need to use this class, they access the unique instance generated by the class. The following C # Code It shows two ways to implement the singleton mode. developers can choose either of them based on their preferences.
Implementation Method 1: Singleton. CS
Using system;
Class singletondemo
{Private Static singletondemo thesingleton = NULL;
Private singletondemo (){}
Public static singletondemo instance ()
{If (null = thesingleton)
{
Thesingleton = new singletondemo ();
}
Return thesingleton;
}
Static void main (string [] ARGs)
{Singletondemo S1 = singletondemo. instance ();
Singletondemo S2 = singletondemo. instance ();
If (s1.equals (S2 ))
{Console. writeline ("See, only one instance! ");
}
}
}
Another equivalent implementation method is Singleton. CS:
Using system;
Class singletondemo
{Private Static singletondemo thesingleton = new singletondemo ();
Private singletondemo (){}
Public static singletondemo instance ()
{Return thesingleton;
}
Static void main (string [] ARGs)
{Singletondemo S1 = singletondemo. instance ();
Singletondemo S2 = singletondemo. instance ();
If (s1.equals (S2 ))
{Console. writeline ("See, only one instance! ");
}
}
}
Compile and execute:
CSC singleton. CS
Get the running result:
See, only one instance!
Deep feelings.