C # design mode: Singleton Mode

Source: Internet
Author: User
How can we ensure that one class can only have one instance?
In the case of multiple threads, how can this problem be solved? Using System;
Using System. Collections. Generic;
Using System. text;

Namespace Singleton
{
Class Singleton
{
// The constructor is private to ensure that it is not explicitly instantiated.
Private Singleton () {}

// Define attributes and return the singleton object
Private   Static Singleton;

Public   Static Singleton instance
{
Get
{
If (Singleton =   Null )
Singleton =   New Singleton ();
Return Singleton;
}
}
}
}

// Multi-threaded Singleton
Namespace Singletonmultithread
{
Class Singleton
{
Private   Static   Object Lockhelper =   New   Object ();

// The constructor is private to ensure that it is not explicitly instantiated.
Private Singleton () {}

// Define attributes and return the singleton object
Private   Static   Volatile Singleton =   Null ;

Public   Static Singleton instance
{
Get
{
If (Singleton =   Null )
{
Lock (Lockhelper)
{< br> If (Singleton = null )
Singleton = New Singleton ();
}
}
Return Singleton;
}
}
}
}

// Classic Singleton implementation: Only applicable to non-argument Constructors (available attributes for extension)
Namespace Classicalsingleton
{
Sealed   Class Singleton
{
Private Singleton () {}
// Inline initialization, followed by a static Constructor
Public   Static   Readonly Singleton instance =   New Singleton ();
}

Class Program
{
Static   Void Main ( String [] ARGs)
{
Singleton S1 = Singleton. instance;
Singleton S2 = Singleton. instance;
If ( Object . Referenceequals (S1, S2 ))
Console. writeline ( " The two objects are the same instance. " );
Else
Console. writeline ( " Two instances with different objects. " );
}
}
}

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.