我有几个数据库——大象、长颈鹿、大猩猩等——每个数据库都有一个输入和结果表,分别命名为 ElephantInputs、ElephantResults、GiraffeInputs、GiraffeResults、GorillaInputs、GorillaResults。我无法控制表命名。
我正在使用 LINQ to SQL 自动生成 ElephantInputs、ElephantResults、GiraffeInputs、GiraffeResults 等类。
我想编写一个类,Processor(),它可以从任何这些数据库中读取输入并对其进行处理。我有一个工厂方法,它根据用户的选择实例化一个处理器。
我做的第一件事是为 Input 和 Result 对象创建一个接口,并为每个数据库创建一个分部类,以便其输入和结果对象实现该接口。这给了我每个动物的通用界面。我还为每个数据库创建了一个存储库类,它具有一些从数据库返回项目的方法。
public interface IBaseInput
{
int ID { get; set; }
string InputA { get; set; }
int InputB { get; set; }
double InputC { get; set; }
}
public interface IBaseResult
{
int ID { get; set; }
string ResultA { get; set; }
int ResultB { get; set; }
double ResultC { get; set; }
}
public interface IRepository<I, R>
where I : IBaseInput
where R : IBaseResult
{
IQueryable<I> GetInputs();
IQueryable<R> GetResults();
}
public partial class GorillaInput : IBaseInput
{
}
public partial class GorillaResult : IBaseResult
{
}
// A concrete repository for Gorillas
public class GorillaRepository : IRepository<GorillaInput, GorillaResult>
{
GorillaDataContext db = new GorillaDataContext(GetConnectionString("Gorillas"));
public IQueryable<GorillaInput> GetInputs()
{
return from p in db.GorillaInputs select p;
}
public IQueryable<GorillaResult> GetResults()
{
return from r in db.GorillaResults select r;
}
}
接下来,我为我的处理器创建了一个接口
public interface IProcessor
{
void Process();
}
这是一个具体的处理器,以及创建它的工厂。
public class Processor<T, I, R> : IProcessor
where T : class, IRepository<I, R>, new()
where P : IBaseInput
where R : IBaseResult
{
public void Process()
{
// Do some stuff ...
T repository = new T(); // Get results from the rater tables
IEnumerable<I> inputs = repository.GetInputs();
IEnumerable<R> results = repository.GetResults();
// Do some stuff with inputs and outputs...
}
}
public static class ProcessorFactory
{
public static IProcessor GetProcessor(string animal)
{
switch (animal) {
case "Elephant":
return new Processor<ElephantRepository, ElephantInput, ElephantResult>();
case "Giraffe":
return new Processor<GiraffeRepository, GiraffeInput, GiraffeResult>();
case "Gorilla":
return new Processor<GorillaRepository, GorillaInput, GorillaResult>();
default:
return null;
}
}
}
最后,这是调用处理器的程序:
class Program
{
public static void Main()
{
IProcessor processor = ProcessorFactory.GetProcessor("Gorilla");
processor.Process();
}
}
我这样做对吗?有没有更简单的方法?谢谢