Common design mode learning-singleton mode, design mode example Mode

Source: Internet
Author: User

Common design mode learning-singleton mode, design mode example Mode

Personal Understanding: only one instance exists in the part implemented in singleton mode during code running.

Application scenarios: Generally, configuration file reading, logging, and some database access connection pools can be designed in singleton mode.

Several implementation methods:

The following uses reading the configuration file as an example.

A configuration file object:

Public class CustomConfig {public string EmailUserName {get; set ;}// public string EmailContentModel {get; set ;}// public string EmailPassword {get; set ;} // email password}

  

Config configuration file:

The Singleton mode is generally divided into two ways: hungry and lazy.

Ele. MeThe Mode instantiates itself when the class is loaded. Its advantage is that it can ensure the uniqueness of the instance without considering the simultaneous access of multiple threads. In terms of call speed and response time, because a singleton object can be created from the beginning, it is better than a lazy singleton object. However, whether or not the system needs to use the singleton object during running, the object needs to be created during class loading, so from the perspective of resource utilization efficiency, the hunger type Singleton is less than the lazy type Singleton, and the loading time may be relatively long due to the need to create a hunger type singleton object during system loading.

First look at the Hungry Man.

Public sealed class SingletonFourth_1 {private static readonly CustomConfig Instance = new CustomConfig (); public static CustomConfig GetInstance () {return Instance;} private SingletonFourth_1 () // disable instantiation {}}

  

Public sealed class SingletonFourth_2 {private static readonly CustomConfig Instance = null; static SingletonFourth_2 () {Instance = new CustomConfig ();} private SingletonFourth_2 () {}// disable External instantiation of public static CustomConfig GetInstance () {return Instance ;}}

These two statements are different, but they are the same.

LazyThis mode is created when it is used for the first time. It does not need to occupy system resources all the time and achieves delayed loading. However, it must handle the problem of simultaneous access by multiple threads, which will affect the system performance.

Public sealed class SingletonFirst {private static CustomConfig _ instance = null; public static CustomConfig Instance {get {if (_ instance! = Null) return _ instance; _ instance = new CustomConfig (); return _ instance ;}} private SingletonFirst () // disable External instantiation {}}

This is a simple lazy. This method won't cause too many problems in a single thread, but it is possible to create multiple instances at the same time when multiple threads access at the same time, in addition, these instances are not the same object. Although the instance created later will overwrite the instance created first, different objects will still be obtained.

Public sealed class SingletonSecond {private static CustomConfig _ instance = null; private static readonly object PadLock = new object (); public static CustomConfig Instance {get {lock (PadLock) {if (_ instance! = Null) return _ instance; _ instance = new CustomConfig (); return _ instance ;}} private SingletonSecond () // disable External instantiation {}}

This writing method is thread-safe, but it will still be instantiated twice when two threads access at the same time, which will produce unnecessary consumption.

Public sealed class SingletonThird {private static CustomConfig _ instance = null; private static readonly object PadLock = new object (); public static CustomConfig GetInstance () {if (_ instance! = Null) return _ instance; // check here to avoid resource waste. if the instance does not exist, it enters the synchronization module {lock (PadLock) {if (_ instance! = Null) return _ instance; // check the synchronization module again. If the synchronization module does not exist, you only need to create one _ instance = new CustomConfig (); _ instance. emailUserName = System. configuration. configurationManager. deleetask[ "EmailUserName"]; _ instance. emailPassword = System. configuration. configurationManager. deleetask[ "EmailPassword"]; _ instance. emailContentModel = System. configuration. configurationManager. deleetask[ "EmailContentModel"]; return _ instance ;}} private SingletonThird () // disable External instantiation {}}

This method is usually used to view a large number of dual-Check Methods. Check the lock before entering the lock. In this way, resource utilization is relatively high, but if you encounter a large number of operations, locking will become a performance bottleneck.

Public sealed class SingletonFifth {private static class Inside {internal static readonly CustomConfig Instance = new CustomConfig () {EmailUserName = System. configuration. configurationManager. deleetask[ "EmailUserName"], EmailPassword = System. configuration. configurationManager. deleetask[ "EmailPassword"], EmailContentModel = System. configuration. configurationManager. deleetask[ "EmailContentModel"]};} public static CustomConfig GetInstance () {return Inside. instance;} private singletongateth () // disable External instantiation {}}

This method is implemented through static internal classes. This method can be used when performance requirements are high to avoid resource waste caused by frequent locks and unlocking.

 

Public sealed class SingletonSixth {private static readonly Lazy <CustomConfig> Lazy = new Lazy <CustomConfig> () => new CustomConfig () {EmailUserName = System. configuration. configurationManager. deleetask[ "EmailUserName"], EmailPassword = System. configuration. configurationManager. deleetask[ "EmailPassword"], EmailContentModel = System. configuration. configurationManager. appSettings ["EmailContentModel"]}); public static CustomConfig GetInstance () {return Lazy. value;} private SingletonSixth () // disable External instantiation {}}

This method uses the Lazy <T> class added by. net4.0, which provides thread-safe call for delayed loading.

The above is the implementation method of the singleton mode that we learned in the past two days. Remember to avoid finding it later.

Reference: http://csharpindepth.com/Articles/General/Singleton.aspx#unsafe

Http://www.cnblogs.com/wuchanming/p/4486357.html

Http://cantellow.iteye.com/blog/838473

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.