Design Mode: single-piece Mode

Source: Internet
Author: User

The Singleton mode requires that a class has only one instance and provides a global access point.

1. Single-threaded Method

 
Public sealed class singlton {static singlton instance = NULL; singlton () {} public static singlton instance {get {If (instance = NULL) {return New singlton ();} return instance ;}}}

This if (instance = NULL) statement is not thread-safe and may generate multiple instances.

2. Thread-safe

 
Public sealed class singlton {static singlton instance = NULL; static readonly object o = new object (); singlton () {} public static singlton instance {get {lock (o) {If (instance = NULL) {return New singlton () ;}return instance ;}}}}

The object instance is created by the first thread to enter. The later thread (instence = NULL) is false and will not be created again. However, this implementation method adds additional overhead and reduces performance.

3. Double Lock

 
Public sealed class singlton {static singlton instance = NULL; static readonly object o = new object (); singlton () {} public static singlton instance {get {If (instance = NULL) {lock (o) {If (instance = NULL) {return New singlton () ;}} return instance ;}}}

AvoidInstanceAn exclusive lock exists in all calls to the property method.

4.Static Initialization

Public sealed class singlton {static readonly singlton instance = new singlton (); static singlton () {} public static singlton instance {get {return instance ;}}}

5. Delayed static Initialization

 
Public sealed class singlton {static singlton () {} public static singlton instance {get {return createsinglton. instance ;}} class createsinglton {internal static readonly singlton instance = new singlton (); static createsinglton (){}}}

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.