The first contact with Singleton mode is the one that I use OC to implement when I am learning iOS. It was a messy study at the time. I just started to think that C # is not a singleton mode, and later saw a lot of things just found that the original C # also has a singleton mode.
The singleton pattern, as its name implies, has only one instance in the entire program life cycle. So how do you implement it in C #?
Implementing singleton Patterns in C # is a simple matter of testing two things, private constructors, and static objects.
The following code example provides a simple singleton pattern for a class.
Public class sigle{ privatestatic _sigle=null; Private Sigle () {} Public Static sigle getinstance () { if(sigle==null) { _sigle=new sigle (); } return _sigle }}
View Code
Look at the code then let's take a thought.
1. Use private constructors to prevent objects of this class from being created by new.
2. Store objects of this class through private field _sigle.
3, through the common static method getinstance to get to the object of this class.
This getinstance is actually very simple. He will first determine if the private field _sigle has stored the object of this class if it is, then return this object directly if it is not a new object and assign a value to the field _sigle.
Maybe everyone would say why is this new? It's very simple. This is where the private constructor of this class can be called.
As you know, static fields, properties, and methods are all part of the class, and the bucket exists throughout the life of the program, so _sigle can only be assigned once and the class can only create one instance at a time throughout the application life cycle.
C # Singleton mode