Definition:
The Singleton mode ensures that only one instance of a class exists in an application. In many operations, such as creating directories and database connections, such single-threaded operations are required. In addition, Singleton can be stateful. In this way, multiple single-piece classes can provide external services like a State Warehouse. For example, if you want the Post Counter in the forum, you need to count the number of items each time you browse, can a single-piece class keep this count? If you want to save this number to the database permanently, you can easily do it without modifying the single-piece interface. In addition, Singleton can also be stateless. The Singleton mode provides tool-based functions, which makes it possible for us to achieve this. The benefit of using Singleton is that it can save memory because it limits the number of instances and facilitates garbage collection. We often see that the factory mode also contains the Singleton mode, because the loaded class actually belongs to the resource.
How to use it?
There are many implementation methods in the Singleton mode. The following describes only one common method.
1 using System;
2
3 namespace ClassLibrary1
4 {
5/** // <summary>
6 // Summary description for Class1.
7 /// </summary>
8 public class Singleton
9 {
10
11 private Singleton ()
12 {}
13 // define your own instance internally. Isn't it strange?
14 // note that this is private for internal calls only
15 private static Singleton instance = new Singleton ();
16 // here we provide a static method for external access to this class, which can be accessed directly.
17 public static Singleton getInstance ()
18 {
19 return instance;
20}
21
22}
23}
24
Considerations for using Singleton:
In some cases, Singleton cannot be used for Singleton. If multiple Singleton objects are loaded by different classes at the same time, there will be many problems. Therefore, the Singleton mode looks simple and easy to use, but it is not easy to use well. You need to have a good understanding of the concepts of classes, threads, and memory.
Previous Article: Design Pattern [Creation pattern] single-piece Pattern