Use wildcard to implement Singleton provider (Original translation)

Source: Internet
Author: User


Original article title: Generic Singleton provider
Address: http://www.codeproject.com/csharp/genericsingleton.asp

Introduction

Many people with different development backgrounds will be familiar with the singleton mode. They will find that each time they want to create a different Singleton class, they have to write the sameCode. With the new generic C #2.0, you can write the same code only once.

Background

There are already manyArticleI have introduced the singleton mode. Maybe the most complete C # version can be found here: "Implementing the Singleton pattern in C #".
There are also more and more articles about C # generics. For example, an article written by ansil of codeproject can be found here: "generics in C #2.0 ".

Use the C #2.0 generic type to reuse the singleton Mode

Using C #2.0 generics makes it possible to implement what I call "Singleton provider. This is a reusable class that can be used to create a singleton class instance and does not need to override the singleton mode code for each specific class. In this way, separating the code of the singleton structure will help to maintain the flexibility of using classes in singleton mode or not in singleton mode.

The Singleton code used here is implemented based on the fifth version of implementing the Singleton pattern in C # mentioned above.

Public   Sealed   Class Singleton
{
Singleton ()
{
}

Public   Static Singleton instance
{
Get
{
Return Singletoncreator. instance;
}
}

Class Singletoncreator
{
// Explicit static constructor to tell C # Compiler
// Not to mark type as beforefieldinit
Static Nested ()
{
}

Internal Static ReadonlySingleton instance= NewSingleton ();
}
}

Based on your understanding of generics, you can find that there is no reason not to replace the type parameter with the typical 'T' in the generics in this Code '. If you do this, the code will become as follows.

Public   Class Singletonprovider < T > Where t: New ()
{
Singletonprovider (){}

Public StaticT instance
{
Get{ReturnSingletoncreator. instance ;}
}

ClassSingletoncreator
{
StaticSingletoncreator (){}

Internal Static ReadonlyT instance= NewT ();
}
}

Note that generic constraints are used here. This constraint forces all types of 'T' to have a public constructor without parameters. Here, the singletoncreator class is allowed to instantiate the type 'T '.

So how to use the singleton provider? To clear how to use it, we need to write a test class. This test class has two parts. The first part is a default constructor used to set the value of the timestamp variable. The second part is a common function used to output timestamp values using "Debug. writeline. This test class means that no matter which thread calls this class public method in a single case at any time, the same value will be returned.

Public   Class Testclass
{
Private   String _ Createdtimestamp;

PublicTestclass ()
{
_ Createdtimestamp=Datetime. Now. tostring ();
}

Public VoidWrite ()
{
Debug. writeline (_ createdtimestamp );
}
}

This class uses the single-instance provider as follows:

Singletonprovider < Testclass > . Instance. Write ();

Focus

I have tested with 100 threads in single-State mode on a hyper-threading dual processor. All threads return the same value, which indicates that this is a single-State Mode Implemented by thread security using generics.

I believe this fully demonstrates how generics help you simplify your code.

History

.

Related Article

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.