Three Singleton implementation methods in C #

Source: Internet
Author: User

This pattern seems to be often discussed. I think the theoretical significance is greater than the actual significance. So let's list three types of writing methods.

1. Common writing

Using System;
Public Class Singleton
{
Private Static Singleton instance;
Private Singleton (){}
Public Static Singleton instance
{
Get
{
If (Instance = Null )
{
Instance = New Singleton ();
}
Return Instance;
}
}
}

 

 


Advantages: 1. It can be extended and inherit from sub-classes. 2. The object will be instantiated as needed. The disadvantage is that it is not thread-safe.

2. Easy Writing

Public Sealed Class Singleton
{
Private Static Readonly Singleton instance = New Singleton ();
Private Singleton (){}
Public Static Singleton instance
{
Get
{
Return Instance;
}
}
}

This is simple and straightforward, and it will only be instantiated during access. To put it bluntly, you can only use the default constructor and cannot add any other operations.

3. Universal implementation

Using System;

Public Sealed ClassSingleton
{
Private Static VolatileSingleton instance;
Private Static ObjectSyncroot =NewObject ();

PrivateSingleton (){}

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

 

Volatile Keywords are very important. When multithreading is used, the actual memory variable will be retrieved again, and the value in the cache will not be accessed.

 

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.