1. Feature: Consider only one instance.
2. Concept: Ensure that a class has only one instance and provides a global point for access.
3. Class Diagram:
4 Program implementation:
1) Lazy type: For the lazy model, we can understand this: the Singleton class is very lazy, only when they need to act, never know how to prepare early. It determines whether an object exists when it is needed, creates an object immediately if it does not, and then returns if an existing object is no longer created and returns immediately.
Lazy mode is created only when an external object requests an instance for the first time. Lazy mode, which is characterized by the slow speed at which objects are obtained at runtime, but faster when loading classes. It consumes resources only a fraction of the time throughout the application's life cycle.
public class Singleton { private static Singleton m_instance; Private Singleton () { //defines the default constructor as private, prevents external calls to it to instantiate other objects } public static Singleton getinstance () { if (m_instance = = null) { m_instance = new Singleton (); } return m_instance; } }
2) A hungry man: for the A Hungry man mode, we can understand this: the Singleton class is very hungry, the urgent need to eat things, so it is the class loaded immediately when the object is created. A hungry man mode, which is characterized by the slow loading of the class, but the speed at which the object is obtained at runtime is relatively fast. It always consumes resources from the time it is loaded to the end of the app.
The definition for sealed prevents derivation because the derivation may increase the instance public sealed class Singleton { private static readonly Singleton m_instance = New Singleton (); Private Singleton () { //defines the default constructor as private, prevents external calls to it to instantiate other objects } public static Singleton getinstance () { return m_instance; } }
3) using lock mechanism
public class Singleton { private static Singleton m_instance; Static readonly Object o = new Object (); Private Singleton () { //defines the default constructor as private, preventing external calls to instantiate other objects} public static Singleton getinstance () { lock (o) { if (m_instance = = null) { m_instance = new Singleton ();} } return m_instance; } }
4) Double Lock
public class Singleton { private static Singleton m_instance; Static readonly Object o = new Object (); Private Singleton () { //defines the default constructor as private, prevents external calls to it to instantiate other objects } public static Singleton getinstance () { //This adds a judge whether the instance exists, only to lock when it does not exist, that is, in the life cycle of this instance, only one lock if (m_instance = = null) { lock (o) { if (m_instance = = null) { m_instance = new Singleton (); }}} return m_instance; } }
Design Pattern Learning notes--a single case design pattern