|
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
// Copyright UZi
namespace UZi.Singleton
{
/// <summary>
/// Generic class for building an instance of T.
/// </summary>
/// <typeparam name="T">The type of the singleton class.</typeparam>
public class SingletonBuilder<T> : ISingletonBuilder<T>
where T : class
{
// should also be protected
protected SingletonBuilder() { }
/// <summary>
/// Creates an instance of T.
/// </summary>
/// <param name="checker">A delegate of type 'SingletonClassConstructorArgsChecker' to check parameter 'args'
/// or null if constructor of T don't have arguments.</param>
/// <param name="args">The arguments for the constructor of T or null if the constructor don't have any argument.</param>
/// <returns>An (initialized) instance of T.</returns>
public T BuildSingleton(SingletonClassConstructorArgsChecker checker, object[] args)
{
// perform some checks...
if (typeof(T).IsAbstract) throw new Exception("Can't create an instance of an abstract class!");
if ((typeof(T).GetConstructors()).Length > 0) throw new InvalidOperationException(
"Operation is invalid for a class with a public constructor!");
if (checker == null && (args != null && args.Length > 0)) throw new ArgumentException(
"If length of parameter 'args' greater than zero parameter 'checker' don't be null!");
if ((checker != null && checker(args)) || (checker == null))
{
return (T)Activator.CreateInstance(typeof(T), BindingFlags.CreateInstance |
BindingFlags.Instance |
BindingFlags.NonPublic, null, args, null);
}
else
throw new ArgumentException();
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
.NET Professional: 'specialist for application development' (a german job title)
I normally develop applications in C# with the .net-framework 2.0+/3.0 and currently databases for MS Sql Server 2005 and MS Access 2003+.
I'm an employee of an office which is working for insurances and which is watching investigations of damages for incorrect items, plausibility and so on and my job is to develop software to automate these processes. I developed for example an application which can extract values from ocr-texts using regular expressions and save these values into a database for later calculations or other processes.