Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize singleton pattern in C #

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to realize the singleton mode in C#. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Introduction of singleton mode

2.1.Motivity (Motivate)

In software systems, there are often such special classes, which must be guaranteed to have only one instance in the system in order to ensure their logical correctness and good efficiency.

How do you bypass regular constructors and provide a mechanism to ensure that a class has only one instance?

This should be the responsibility of the class designer, not the user.

2.2, intention (Intent)

Ensure that there is only one instance of a class and provide a global access point for that instance. "Design pattern GoF"

2.3.Structure diagram (Structure)

2.4. The composition of the model

(1), singleton instance (Singleton): there is only one type in this pattern, which is the Singleton type, and there is only one instance of this class, which can be obtained through the Instance () method.

2.5. Code implementation of singleton pattern

Since it is a single instance, it will definitely involve multithreading, so let's write the code step by step. Let's take a look at the implementation of single-threaded Singleton mode. The code is as follows:

The private instance constructor is shielded from external calls, and the implementation of the above singleton pattern is indeed perfect in a single-threaded environment and meets the needs of our single-threaded environment.

Several key points of single-threaded singleton mode:

(1) the instance constructor in Singleton mode can be set to protected to allow subclasses to derive.

(2) generally, Singleton mode does not support ICloneable interface, because this may lead to multiple object instances, which is contrary to the original intention of Singleton schema.

(3) the Singleton schema generally does not support serialization, because it may also lead to multiple object instances, which is also contrary to the original intention of the Singleton schema.

(4) Singletom mode only considers the work of object creation, not the work of object destruction. Why do you do this? because the Net platform supports garbage collection, there is generally no need to destroy it.

(5) unable to deal with multithreaded environment: in multithreaded environment, it is still possible to get multiple instance objects of Singleton class by using Singleton pattern.

If you put it in a multithreaded environment, the problem will arise. Because when two threads run the GetInstance method at the same time, both threads return true when judging the condition (uniqueInstance = = null), and both threads will create instances of Singleton, which goes against the original intention of our singleton model. To solve this problem, just let the GetInstance method run only one thread at a time. Let's take a look at the implementation of the multithreaded Singleton pattern, as follows:

The above solution can indeed solve the multithreading problem, but the above code for each thread will lock the thread helper object locker and then determine whether the instance exists, which is not necessary for this operation, because when the first thread creates an instance of this class, the subsequent thread only needs to uniqueInstance==null directly at this time. At this time, there is no need to lock the thread helper object before judging, so the above implementation adds additional overhead and loses performance. In order to improve the defects of the above implementation, we only need to add a sentence (uniqueInstance==null) in front of the lock statement to avoid the additional overhead of the lock. In this implementation, we call it "Double Check". Let's take a look at the implementation code:

Volatile embellishment: the compiler will fine-tune the order of the code when compiling the code, using volatile embellishment to ensure a strict order. A variable defined as volatile means that the variable may be changed unexpectedly so that the compiler does not assume the value of the variable. To be precise, the optimizer must carefully reread the value of the variable every time it uses it, rather than using a backup saved in the register.

3. The class of singleton pattern is implemented in C #.

Now let's see how to use the features of the C # language to implement the singleton Singleton pattern.

Inline initialization is actually initializing static fields in a static constructor. As long as you want to access static fields, you must have executed the static constructor before. This can also accurately ensure that you can get an instance when you use it, and if you don't use it, you won't instantiate the object, that is, the function of delayed loading. It can also support a multithreaded environment, because only one thread can execute the static constructor, it is impossible for multiple threads to execute the static constructor, and it feels like the program has automatically locked us.

One of its drawbacks is that it does not support parameterized instantiation. In .NET, static constructors can only declare one, and must be parameterless and private. Therefore, this approach only applies to constructors with no parameters.

It should be noted that HttpContext.Current is a singleton, they are implemented through the extension of Singleton, their singleton does not cover all areas, but only for some local areas, it is a singleton, and there will be different instances in different fields.

IV. Extension of Singleton mode

(1) extend one instance to n instances, such as the implementation of object pool. (n does not mean an infinite number of instances, but a fixed number)

(2) transfer the call of the new constructor to other classes, such as multiple classes working together, where a local environment only needs to have one instance of a class.

(3) the core of understanding and extending the Singleton pattern is "how to control users' arbitrary calls to the instance constructor of a class using new".

Fifth, the main points of the realization of the singleton model

1. The Singleton pattern restricts, not improves, the creation of classes.

2. The instance constructor in the Singleton class can be set to Protected to allow subclasses to derive.

3. Singleton mode generally does not support Icloneable interface, because this may lead to multiple object instances, which is contrary to the original intention of Singleton schema.

4. Singleton schema generally does not support serialization, which may lead to multiple object instances, which is also contrary to the original intention of Singleton schema.

5. Singleton only considers the management of object creation, but does not take into account the management of destruction. In terms of the cost of platforms and objects that support garbage collection, we generally do not need to carry out special management of their destruction.

6. The core of understanding and extending the Singleton pattern is "how to control users' arbitrary calls to the constructor of a class using new".

7. You can simply modify a Singleton to have a few instances, which is permissible and meaningful.

1], the advantages of singleton model:

(1) instance control: Singleton prevents other objects from instantiating their own copies of Singleton objects, thus ensuring that all objects access unique instances

(2) flexibility: because the class controls the instantiation process, the class can modify the instantiation process more flexibly.

2], the shortcomings of the singleton model:

(1) overhead: although the number is small, it will still require some overhead to check whether there is an instance of the class every time the object requests a reference. You can solve this problem by using static initialization.

(2) possible development confusion: when using singleton objects (especially those defined in the class library), developers must remember that they cannot instantiate objects using the new keyword. Because the library source code may not be accessible, application developers may accidentally find themselves unable to instantiate this class directly.

(3) object lifetime: Singleton cannot solve the problem of deleting a single object. Because it contains a reference to the static private field, the static field cannot be reclaimed by CLR, and the instance will last as long as the application life cycle.

3], the use of singleton mode:

(1) when a class can have only one instance and the customer can access it from a well-known access point.

(2) when the only instance should be extensible by subclassing, and the customer should be able to use an extended instance without changing the code.

The above is how to achieve the singleton pattern in C# shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report