C # design pattern series: Singleton)

Source: Internet
Author: User

1. Introduction to single-piece Mode

Singleton defines that a class has only one instance and provides a global access point.

Features of the single-piece mode:
1> A single-piece class can only have one instance.
2> A single-piece class must create a unique instance.
3> A single-piece class must provide a unique instance for all other objects.

Single-piece mode application:
1> each computer can have several printers, but only one printer spooler can be used to prevent two print jobs from being output to the printer at the same time.

2,Single PieceMode Structure

3. Single-piece mode implementation

C # key points of single-piece mode:

A singleton class has a private non-argument constructor. This prevents the class from being instantiated by other classes, and the singleton class should not be inherited, if a singleton class permits inheritance, each subclass can create instances, which violates the "unique instance" Principle in the singleton mode.

You can use sealed to modify a pair of single-piece classes to prevent them from being inherited.

A static variable is used to save the reference of a single instance.

A public static method is used to obtain a single instance reference. If the instance is null, a single instance is created.

 

C # Six common implementation methods for single-piece mode:

1> non-thread security

Singleton. CS

 Using System;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. text;  Namespace  Designpatterns. singletonpattern. First {  ///   <Summary>      ///  Single-piece mode Implementation Method 1: Because this implementation method is not thread-safe, it is not recommended in practical applications.  ///   </Summary>     Public   Sealed   Class  Singleton {  Private   Static  Singleton _ instance;  //  Set the constructor to private to prevent Object Instantiation through new.          Private  Singleton (){}  Public   Static  Singleton instance (){  // Use delay Initialization  //  Note: Non-thread security              If (_ Instance = Null  ) {_ Instance = New  Singleton ();}  Return  _ Instance ;}}} 

Program. CS

 Using  System;  Using  System. Collections. Generic; Using  System. LINQ;  Using  System. text;  Namespace  Designpatterns. singletonpatternapp {  Class  Program {  Static   Void Main ( String  [] ARGs) {designpatterns. singletonpattern. First. Singleton S1 =Designpatterns. singletonpattern. First. Singleton. instance (); designpatterns. singletonpattern. First. Singleton S2 = Designpatterns. singletonpattern. First. Singleton. instance ();  If (S1 = S2) {console. writeline (  "  The object is the same instance.  "  );}}}} 

The preceding implementation method is applicable to a single-threaded environment. In a multi-threaded environment, multiple instances of the singleton class may be obtained. If there are two threads to judge at the same time (null = _ Singleton) and the result is true, then both threads will create Singleton-like instances, this violates the singleton mode "unique instance" principle.

2> simple thread security

 Using System;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. text;  Namespace  Designpatterns. singletonpattern. Second {  Public   Sealed   Class  Singleton {  Private   Static Singleton _ instance;  //  Lock synchronization object          Private   Static   Readonly   Object _ Synclock = New   Object  ();  //  Constructor is 'private'          Private  Singleton (){}  Public  Static  Singleton instance (){  //  Support Multithreaded Applications through  //  'Double checked locking' pattern which (once  //  The instance exists) avoids locking each  //  Time the method is invoked              If (_ Instance = Null  ){ Lock  (_ Synclock ){  If (_ Instance = Null  ) {_ Instance = New  Singleton ();}}}  Return  _ Instance ;}}} 

The above implementation method is thread-safe. First, a static read-only process auxiliary object is created, because lock ensures that when a thread is locatedCodeAnother thread cannot enter the critical section (synchronous operation ). If other threads attempt to enter the locked code, it will wait until the object is released. This ensures that multiple object instances are not created under multiple threads. However, this implementation method requires synchronization, which will affect the system performance bottleneck and increase additional overhead.

 

4. Summary of single-piece Mode

Note:

1> do not use Singleton mode to access global variables. This violates the intention of the singleton mode and is best placed in the static members of the corresponding class.

2> do not make the database connection into a single instance, because a system may have multiple connections to the database, and in the case of a connection pool, release the connection as soon as possible. Because the static member storage class instance is used in singleton mode, resources may not be released in time.

5. References

Http://csharpindepth.com/Articles/General/Singleton.aspx

Http://www.dofactory.com/Patterns/Patterns.aspx

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.