Practical generic Singleton class

Source: Internet
Author: User
The Singleton mode is one of the most common design patterns. We often write this type of code. because its basic principle is to save a static object instance, we can use generics to write a general Singleton class. the code is simple: public class Singleton <t>
...{
Static readonly T _ t;
Static Singleton ()
...{
_ T = construct ();
}

Public static t getinstance ()
...{
Return _ t;
}

Private Static t construct ()
...{
Type type = typeof (t );
Constructorinfo ctor;
Ctor = type. getconstructor (bindingflags. instance | bindingflags. Public | bindingflags. nonpublic,
Null, new type [0], new parametermodifier [0]);
System. Diagnostics. Debug. Assert (ctor! = NULL, "error in enls. Basic. Singleton. Construct ().");
Return (t) ctor. Invoke (new object [0]);
}
} Because specialized generic classes are of different types, Singleton <tuple <int> and Singleton <tuple <int, long> are different, therefore, _ t in these two classes are different static instances. then, the Construct method calls the common or private default constructor parameters through reflection to create a new instance. why is there a public constructor? This is to use the nullobject mode. for example, for convenience, I want to add a method to the tuple base class to the empty object public static tuple getnullinstance <_ tuple> () Where _ tuple: tuple
{
Return Singleton <_ tuple>. getinstance ();
} With this empty object, I can use the traversal control function described in the previous article more simply. public ienumerable <control> iterator <_ tuple> (control basectl) Where _ tuple: tuple
...{
Tuple = tuple. getnullinstance <_ tuple> ();
Foreach (control C in basectl. Controls)
...{
If (! Tuple. hastype (c ))
...{
Foreach (control C1 in iterator <_ tuple> (c ))
Yield return C1;
}
Else
Yield return C;
}
} In this way, you can conveniently call foreach (control C in this. iterator <tuple <Textbox, Treeview, checkbox> (this ))
MessageBox. Show (C. Name );

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.