The concept of "Singleton" is that there is only one copy of data within the specified range.
The "specified range" may be process, AppDomain, thread, or call. Different technologies may be used to create a single instance within a specified range. For example, a common static attribute Instance can provide a very happy range for each AppDomain; a static field modified by ThreadStaticAttribute can provide a range for each thread; and a CallContextStaticAttribute (which must be customized, to provide the scope of each call and so on.
Today, we will discuss how the implementation of Singleton is different from that of these scopes. Next, let's assume that a singleton is implemented in the unique AppDomain in a process.
In terms of implementation, there are three methods for "Singleton:
1. static class. All methods, attributes, and variables in this class are in one copy.
2. A static Insatnce attribute or the getInstance () method, that is, the standard Singleton mode.
3. Monostate mode.
For 1, there is nothing to say, there is no inheritance, there is no polymorphism, relatively rigid, initialization when the class is used for the first time.
2. It can be inherited and has polymorphism. The problem is that all the derived classes must implement the Instance attribute or the getInstance method to make the derived classes Singleton. It is initialized when the Instance attribute is used for the first time or the getInstance method is called.
3. It can be inherited and polymorphism. Multiple instance objects share the same static variables internally (similar to the metadata mode. Flyweight: Every time I see this Chinese translation, I admire it.) There is only one copy of the data. A derived class is born with Singleton.
Based on the requirements, a simple application is directly 1; for 2, there has not been a situation where 1 cannot be replaced, basically there is no abnormal demand to reload some functions of Singleton; for 3, the only difference is that part of the data is the range of each AppDomain, and part is the "Singleton" of each call. For different calls, the data in each "Singleton" of each call is different.