Using C # 2.0 generics to implement single-mode reuse

Source: Internet
Author: User

Introduced

Many people with different development backgrounds are more familiar with the single case pattern. They will find that each time they want to create a different single instance class, they have to write the same code. With the new C # 2.0 generics, you can implement the same code only once.

Using C # 2.0 generics to complete the reuse of a single case pattern

Using the generics of C # 2.0 makes it possible to implement what I call a single instance provider. This is a reusable class that you can use to create a singleton class instance that does not need to override the singleton pattern code for each particular class. This separation of the code from the single case structure will help to keep the class in a single case mode or use the class in a single case mode.

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 readonly Singleton instance = new Singleton();
 }
}

Based on the understanding of generics, you can see that there is no reason not to replace the type parameter in the code with the typical ' T ' in the generic form. If you do this, the code becomes the following.

public class SingletonProvider<T> where T : new()
{
 SingletonProvider() { }
 public static T Instance
 {
  get { return SingletonCreator.instance; }
 }
 class SingletonCreator
 {
  static SingletonCreator() { }
  internal static readonly T instance = new T();
 }
}

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.