C # Singleton Model lazy/a hungry man

Source: Internet
Author: User

Before you can use a design pattern, you must first understand the advantages of using it:

1, the singleton mode is to ensure that the entire application life cycle, at any time, the specified class has only one instance object, reducing the creation of objects, thereby reducing the cost of program memory.

2, single case mode is a common software design mode. In its core structure, there is only one special class that is called a singleton. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.
3, plainly, is to ensure that a class has only one instance, and provides a global access point for that instance.

Application Scenarios:
1. Task Manager for Windows is a typical singleton mode, and only one window can be opened at any time.
2. Windows Recycle Bin (Recycle Bin) is also a typical single-instance application. During the whole system operation, the Recycle Bin maintains the only one instance.


3. The website counter, generally also uses the Singleton pattern realization, otherwise difficult to synchronize.
4. Application of the log application, the general use of single-case mode implementation, which is generally due to the shared log file is open, because there can only be one instance to operate, otherwise the content is not good to append.
5. The Web application's configuration object reads, generally also applies the singleton pattern, this is because the configuration file is the shared resource.
6. Database connection pooling is generally designed with a singleton pattern, because database connections are a database resource. Database software system in the use of database connection pool, mainly to save the open or close the database connection caused by the efficiency of loss, this loss of efficiency is very expensive, because how to use a single case mode to maintain, can greatly reduce this loss.
7. Multithreaded thread pools are generally designed with a singleton pattern, because thread pooling is convenient for controlling the threads in the pool.
8. The file system of the operating system is also a specific example of a large single-instance pattern implementation, and an operating system can have only one file system.

Code implementation (Lazy mode: Instantiate itself when referenced for the first time):
1. Define the constructor method of the class as a private method so that other code cannot instantiate the object of the class by calling the constructor of the class, only the static method provided by the class to get the unique instance of the class; (prevent callers from instantiating directly)

2. Provide a static method within this class, and when we call this method, if the class holds a reference that is not empty, return this reference, if the class persisted reference is empty, create an instance of the class and give the instance a reference to the class to keep.
3. Create a Visitor object (for locking to prevent concurrency)

4. Create a global access point (output instance): So this method must not be private, protected, or other classes cannot call the method, and it has to be a static method because this class constructor is

The private external cannot instantiate this class (as already mentioned), so the method can only be called by the class name. (dot) method name. Otherwise, the class you're creating is a waste class that no one else can use.

Use a double lock to prevent concurrency problems that occur with multi-threaded calls:

When single is null and two threads are called at the same time
GetInstance method, they will all be able to pass the
Judgment of a heavy single==null, and then due to the lock
Mechanism, the two threads have only one entry, and the other
Waiting in line, one of them must enter
And come out after another to enter. And at this point, if
Without the second-heavy single is null judgment,
The first thread creates the instance, and the second thread
Or you can continue to create a new instance, there is no
To achieve the purpose of a single case.

5. Call

(A Hungry man mode: instantiate itself when loading)

Note : At this point, the service object has been assigned a value for the class instance at the time of the program's loading (but only once, because static readonly is assigned with a statically constructed function)

This implementation is similar to the previous example and addresses the two basic issues that a singleton mode view solves: Global access and instantiation control, and public static properties provide a global access point for accessing the instance. The difference is that it relies on the common language runtime to initialize variables. Because the constructor method is private, the Singleton class cannot be instantiated outside of the class itself, so the variable refers to a unique instance that can exist in the system. Note, however, that the instance variable is marked as ReadOnly, which means that the variable can only be assigned during static initialization or in the constructor. Since this method of static initialization is to instantiate itself when it is loaded, so the image is called the A Hungry man-type singleton class, the original singleton mode processing mode is to be referenced in the first time, it will be instantiated, so it is called the lazy type of singleton class.

Because of the A Hungry man type, which is the static initialization method, it is the object that the class is loaded on, so the system resources should be occupied in advance. Then lazy, and will face the security of multi-threaded access, need to do double locking such processing to ensure security. So which approach to use depends on the actual demand. From the C # language perspective, a hungry man-type singleton classes are sufficient to meet our needs.

C # Singleton Model lazy/a hungry man

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.