Singleton mode introduction
Singleton pattern is a creative design pattern that mainly ensures that there is only one instance in a class and provides a global access point to obtain the instance. In C#, there are many ways to implement singleton mode, each with its specific usage scenarios and precautions.
The role of design patterns
- Improve code reusability: By defining a standard set of solutions, design patterns enable the same or similar problems to reuse the same code structure or logic in different projects.
- Enhanced code readability: Design patterns express complex code logic in clear and concise ways, making it easier for other developers to understand and maintain code.
- Improve the maintainability of the system: The design model follows certain design principles, such as the opening and closing principle, the Richter replacement principle, etc. These principles help reduce the coupling degree of various parts of the system and improve the scalability and maintainability of the system.
Hungry singleton mode
A singleton of the Hungry style creates an instance when the class is loaded. The advantage is that the implementation is simple, and the disadvantage is that if the instance is not used, it will cause waste of resources.
/// <summary> /// Hungry singleton mode /// </summary> public class SingletonEager { private SingletonEager() { } private static readonly SingletonEager _instance = new SingletonEager(); public static SingletonEager Instance { get { return _instance; } } public void DoSomething() { ("Hungry Man-style singleton mode."); } }
Lazy singleton mode
Lazy singletons create instances when they are first visited. For thread safety, a lock mechanism is usually required.
/// <summary> /// Lazy singleton mode /// </summary> public class SingletonLazy { private SingletonLazy() { } private static SingletonLazy? _instance; private static readonly object _lockObj = new object(); public static SingletonLazy Instance { get { if (_instance == null) { lock (_lockObj) { if (_instance == null) { _instance = new SingletonLazy(); } } } return _instance; } } public void DoSomething() { ("Laggy singleton pattern."); } }
Lazy loading singleton mode
If you are using .NET 4 (or later), you can use the Lazy class to implement thread-safe lazy loading singleton pattern.
/// <summary> /// Lazy loading singleton mode /// </summary> public sealed class SingletonByLazy { private static readonly Lazy<SingletonByLazy> _lazy = new Lazy<SingletonByLazy>(() => new SingletonByLazy()); public static SingletonByLazy Instance { get { return _lazy.Value; } } private SingletonByLazy() { } public void DoSomething() { ("Lazy loading singleton mode."); } }
This is the end of this article about the various implementations of C# singleton model. For more related contents of C# singleton model, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!