Singleton mode, multi-thread Singleton, dual lock Singleton, and factory Singleton creation context ., Multi-thread Context

Source: Internet
Author: User

Singleton mode, multi-thread Singleton, dual lock Singleton, and factory Singleton creation context ., Multi-thread Context
Single-sample mode definition

Ensure that a class has only one instance and provides a global access point to it.

Generally, we can make a global variable to make an object accessible, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself store its unique instance. This class ensures that no other instance can be created and it can provide a method to access the instance. This is the singleton mode.

 

Simple implementation of single-sample mode

The Singleton class defines a GetInstance operation that allows customers to access its unique instance. GetInstance is a static method and is mainly responsible for creating its own unique instance.

Public class Singleton {private static Singleton _ instance; private Singleton () // private constructor to prevent the outside world from using the new keyword to create an instance {} public static Singleton GetInstance () {return _ instance ?? (_ Instance = new Singleton ());}}
Test code
Public void Myaction () {var s1 = Singleton. getInstance (); var s2 = Singleton. getInstance (); if (s1 = s2) {Console. writeLine ("the two objects are the same! ");} Console. Read ();}

 

Singleton for Multithreading

The preceding code runs in a multi-threaded program. When multiple threads simultaneously access the Singleton class and call the GetInstance () method, multiple instances may be created.

In this case, we can give a lock to the process. here we need to understand the meaning of the lock statement. lock ensures that when the current thread is located in the Code critical section, the other thread does not enter the critical section. If other threads attempt to enter the locked code, it waits until the object is released.

Simple implementation
Public class Singleton {private static Singleton _ instance; // a static read-only process auxiliary object private static readonly object SyncRoot = new object () during program execution; private Singleton () // private constructor to prevent external users from using the new keyword to create an instance {} public static Singleton GetInstance () {lock (SyncRoot) // only one thread can enter the {_ instance = _ instance ?? (_ Instance = new Singleton ();} return _ instance ;}}

 

Double-Check Locking)

Through the above example, it is not difficult to find that every time we call the GetInstance () method, we need to lock this method, which obviously affects the performance. Therefore, we need to make another judgment.

Simple implementation
Public class Singleton {private static Singleton _ instance; // a static read-only process auxiliary object private static readonly object SyncRoot = new object () during program execution; private Singleton () // private constructor to prevent external users from using the new keyword to create an instance {} public static Singleton GetInstance () {if (_ instance = null) // first determine whether the instance exists, there is no lock processing {lock (SyncRoot). // only one thread can access the {_ instance = _ instance ?? (_ Instance = new Singleton () ;}return _ instance ;}}

 

 

Create data context for factory Singleton

We often need to create a single data context in the development process. Therefore, we use a simple factory to create a data context.

Simple implementation
Public class DbFactory {private static readonly object SyncRoot = new object (); private DbFactory () {}# region get the current context object /// <summary> // The context object obtained by the singleton factory // consider multithreading /// </summary> // /<returns> </returns> public static SiyoukuContext GetCurrentDbContext () {var context = (SiyoukuContext) CallContext. getData ("DbContext"); // obtain if (context = null) from the data slot {lock (SyncRoot) // double lock {if (context = null) {// if not, a context object context = new SiyoukuContext (); CallContext is instantiated. setData ("DbContext", context) ;}} return context ;}# endregion}

 

 

This document summarizes the singleton mode.

Main Site: http://www.siyouku.cn

Permanent more detailed address: http://siyouku.cn/article/6812.html

Related Article

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.