If a class can always create only one instance, this class is called a singleton class. In some special cases, the system will not allow the freedom to create an object of a class, 21 can only create an object for the class, at this point, you can use the constructor method of the class using the private adornment, all its construction methods are hidden. Once the constructor of the class is hidden, you need to provide a public method as an access point for the class that creates the object for the class, and the method must use the static adornment (because the object does not exist before the method is called, so it is not possible to call the method an object, only a class), except that The class must also cache objects that have already been created, otherwise he will not be able to know if a country object has ever been created, and the value cannot be guaranteed to create an object. To do this, the class needs to use a property to hold the object that was created, and because the property needs to be accessed by the static method above, you must use the static modifier, based on the above description, to create a singleton class:
class Single {
Use a variable to cache the created instance
private static Single ;
Use the private adornment to hide the construction method
Private Single () {
}
Provides a static method for returning a single instance, which can be given a custom control that guarantees that the value produces a singleton object
Public Static Single singlet () {
if ( single = null) {
single = new single ();
}
return Single;
}
}
Public class singletest {
Public static void main (string[] args) {
Creating a single object cannot be constructed by means of a singlet method
Single S1 = single. Singlet ();
Single S2 = single. Singlet ();
System. out. println (S1 = = s2);
}
}
Program output: True
The custom control provided by the singlet method above guarantees that the single class can produce only one instance, so the single object produced in the main method of the Singletest class is actually the same object as seen in two times
Single-Instance class