[Design mode]-SingleTon (SingleTon Mode)

Source: Internet
Author: User

1. Intention of the singleton

1.1 The significance of Singleton is that the singleton mode class only has one instance and cannot use new to create other instances. This can save resources and constrain user instantiation.

1.2 single-instance application scenarios can be some global public classes, such as 1. Application Log classes, 2. configuration file loading and reading classes, and 3. cache container classes.

2. Notes

2.1 The SingleTon class cannot implement the ICloneable interface. If this is done, it will be very contradictory.

2.2 serialization and deserialization are not allowed because the deserialized instance is a new instance.

2.3 constructor Parameters

2.4 object destruction and garbage collection

3. Implementation Code and related instructions

/*************************************** **************************************** Author: wjn * Create: 23:02:27 * Title: [design mode]-SingleTon (SingleTon mode) * Description: Some records about SingleTon mode * CopyRight: wjn2010.cnblogs.com * Reference: http://csharpindepth.com/Articles/General/Singleton.aspx * http://www.cnblogs.com/TomXu/archive/2011/12/19/2291448.html * Notes: Codes based on. net Framework 4.0 **** **************************************** * ********************************/Using System; using System. linq; using System. reflection; using System. threading. tasks; namespace SingleTonDemo {/// <summary> /// single-thread version (single-instance prototype, thread unsafe) /// </summary> sealed class SingleTon {private static SingleTon instance; // <summary> // private constructor, make it impossible for external users to construct a private SingleTon () {}/// <summary> using new /// </Summary> public static SingleTon Instance {get {return instance ?? (Instance = new SingleTon () ;}}/// <summary> // thread-safe version (double check) /// here, thread security means that the singleton object itself is thread-safe, but the singleton member (variable) is not thread-safe, all Singleton versions have this problem. /// if you need to ensure thread security when a member is required, the simplest method is to lock the instance. /// </Summary> sealed class SingleTon {// <summary> // fields declared as volatile are not restricted by Compiler Optimization (assuming that they are accessed by a single thread, /// For details, refer to the link http://msdn.microsoft.com/zh-cn/library/x13ttww7.aspx "/// </summary> private volatile static SingleTon instance; /// <summary> /// mutex /// </summary> private static readonly object mutex = new object (); private SingleTon () {} public static SingleTon Instance {get {if (instance = null) {l Ock (mutex) {if (instance = null) {instance = new SingleTon () ;}} return instance ;}}} /// <summary> /// CLR version. C # The Compiler calls the static constructor to assign values to the field before accessing the static field, there will also be only one thread to call the static constructor, and subsequent threads will not call it again. /// Decompile IL to see a command named beforefieldinit // </summary> sealed class SingleTon {public static readonly SingleTon Instance = new SingleTon (); private SingleTon () {}}/// <summary> // delay loading version, construct an instance through internal classes /// </summary> sealed class SingleTon {private SingleTon () {} public static SingleTon Instance {get {return Nested. innerInstance;} private static class Nested {static Nested () {} internal static re Adonly SingleTon InnerInstance = new SingleTon ();}} /// <summary> /// build a version of delayed loading and thread-safe by using the Lazy class /// for details about Lazy, refer to the http://msdn.microsoft.com/en-us/library/dd997286.aspx /// </summary> sealed class SingleTon {private SingleTon () {} private static readonly Lazy <SingleTon> lazy = new Lazy <SingleTon> () => new SingleTon (); public static SingleTon Instance {get {return lazy. value ;}}/// <summary> // /Generic version (Handling constructor issues) /// </summary> /// <typeparam name = "T"> </typeparam> public abstract class Singleton <T> {private static readonly Lazy <T> instance = new lazy <T> (() ==>{ var ctors = typeof (T ). getConstructors (BindingFlags. instance | BindingFlags. nonPublic | BindingFlags. public); if (ctors. count ()! = 1) throw new InvalidOperationException (String. format ("Type {0} must have exactly one constructor. ", typeof (T); var ctor = ctors. singleOrDefault (c =>! C. getParameters (). any () & c. isPrivate); if (ctor = null) throw new InvalidOperationException (String. format ("The constructor for {0} must be private and take no parameters. ", typeof (T); return (T) ctor. invoke (null) ;}); public static T Instance {get {return instance. value ;}}/// <summary> // demonstrate the thread insecurity of the SingleTon member. // </summary> class SingleTon: singleton <SingleTon> {static readonly object mutex = new object (); public int Counter {get; private set;} private SingleTon () {} public void Increment () {lock (mutex) {Counter ++ ;}}} /// <summary> /// test class /// </summary> class Program {static void Main (string [] args) {Parallel. for (0, 1000, result => {for (var I = 0; I <1000; I ++) {SingleTon. instance. increment () ;}}); // If the lock is not applied to Increment (), the value is generally less than 1000*1000 Console. writeLine (SingleTon. instance. counter); Console. readKey ();}}}

4. Expansion

  A singleton is a design model, so it cannot stay above the concept. Compared with an instance, a singleton represents a control over the instance structure, making it impossible for users to construct instances at will, avoid excessive waste and unnecessary problems. Therefore, in the singleton mode, we should see an object management mode. A singleton mode can also be extended to multiple instances, built as an object pool. In fact, at present, the thread pool or connection pool in. Net Framework puts a fixed number of objects in the data structure such as the stack or queue for maintenance, and has reached the goal of making better use of these scarce resources.

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.