Object obj= QSDBFactoryReflection.Instance.Create("Factory." + Name);//利用反射
// QSDBFactory.Instance.Create(Name);//不用反射
namespace Factory
{
#region Example 2.简单工厂
/// <summary>
/// //不用反射的工厂类
/// </summary>
public class QSDBFactory
{
private static QSDBFactory instance = new QSDBFactory();
public static QSDBFactory Instance
{
get { return instance; }
}
public IQSDB Create(string name)
{
switch (name)
{
case "IMPORT_JOB":
return new IMPORT_JOB();
case "DCCHECK":
return new DCCHECK();
case "OCEAN":
return new OCEAN();
default:
throw new Exception("Wrong name.");
}
}
}
/// <summary>
/// 反射工厂类
/// </summary>
public class QSDBFactoryReflection
{
private static QSDBFactoryReflection _instance = new QSDBFactoryReflection();
public static QSDBFactoryReflection Instance
{
get { return _instance; }
}
public IQSDB Create(string Name)
{
IQSDB qsdb = null;
try
{
Type type = Type.GetType(Name, true);
qsdb = (IQSDB)Activator.CreateInstance(type);
}
catch (TypeLoadException e)
{
Console.WriteLine("exception caught - {0}", e.Message);
}
return qsdb;
}
}
public class IMPORT_JOB : IQSDB
{
public IMPORT_JOB()
{
Console.WriteLine("IMPORT_JOB");
}
public void Execute() { Console.WriteLine("Execute IMPORT_JOB!"); }
}
public class DCCHECK : IQSDB
{
public DCCHECK()
{
Console.WriteLine("DCCHECK");
}
public void Execute() { Console.WriteLine("Execute DCCHECK!"); }
}
public class OCEAN : IQSDB
{
public OCEAN()
{
Console.WriteLine("OCEAN");
}
public void Execute() { Console.WriteLine("Execute OCEAN!"); }
}
#endregion
}