C # design mode (1) + single-case mode

Source: Internet
Author: User

What is a singleton mode: ensure that only one instance object exists for a class and provides a global access point;

Application Environment: when only one object, one instance, is needed

For example: WinForm can only create one form at a time, only when one instance object is needed

Code:

  Public classsingleton{//Determine whether the instantiation of a class is unique through a static private variablePrivate StaticSingleton MYINSTANCD;PrivateSingleton () {}//defines a global method that provides external access to a class Public StaticSingleton getinstance () {//if empty, the object is instantiated, otherwise the object is returnedif(myinstancd==NULL) {MYINSTANCD=NewSingleton ();}returnMYINSTANCD;}} 

Cons: in multi-threaded time Two threads simultaneous access is empty and multiple instances are created

workaround : Add lock

 Public classsingleton{//Determine whether the instantiation of a class is unique through a static private variablePrivate StaticSingleton MYINSTANCD;//determine if locking ensures thread synchronizationPrivate Static ReadOnly ObjectMyLock =New Object();PrivateSingleton () {}//defines a global method that provides external access to a class Public StaticSingleton getinstance () {//when lock is locked, the thread hangs and no multiple instance objects appearLock(myLock) {//if empty, the object is instantiated, otherwise the object is returnedif(MYINSTANCD = =NULL) {MYINSTANCD=NewSingleton ();}}returnMYINSTANCD;}} 

Reference

C # design mode (1) + single-case mode

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.