Linq到SQL中DAO的工厂
本文关键字:工厂 DAO SQL Linq | 更新日期: 2023-09-27 18:30:03
我正在努力创建以下情况:
首先,有几个Linq-to-SQL表对象做着几乎相同的事情。让我们把它们称为products_something、products_somewingElse等
其次,有一个接口可以执行Products DAO的所有常见方法。首先,我试图为所有产品只创建一个DAO,因为我可以在另一层(DAL)上处理它的差异。但由于Linq-to-SQL需要强类型引用,因此我最终为每种类型的产品使用一个DAO。我真的不知道是否有可能做到我之前提到的。
最后,我有一个ProductsDaoFactory,它根据客户端(用户视图)的选择实例化正确的ProductDao。由于我不知道在运行时会选择哪种类型的产品,我创建了一个通用工厂来处理它
这是代码:
public enum ProductEnum
{
SimpleProduct, ComplexProduct, RevisedProduct, BrokenProduct
}
public interface IProducts<T>
{
T GetProductById(int id);
IQueryable<T> GetAllProducts(string product_name, DateTime product_age);
//Several other common methods
}
public static class ProductFactory
{
//This won't compile because i have to set what's the type of the DAO i want
public static IProducts<T> GetProductDAO(ProductEnum product)
{
switch (product)
{
case ProductEnum.SimpleProduct:
return new SimpleProductDAO();
case ProductEnum.ComplexProduct:
return new ComplexProductDAO();
case ProductEnum.RevisedProduct:
return new RevisedProductDAO();
case ProductEnum.BrokenProduct:
return new BrokenProductDAO();
default:
break;
}
return null;
}
}
public class SimpleProductDAO : IProducts<SimpleProductDAO>
{
public SimpleProductDAO GetProductById(int id)
{
//Implementation
}
public IQueryable<SimpleProductDAO> GetAllProducts(string product_name, DateTime product_age)
{
//Implementation
}
}
问题是:我不能定义工厂方法的返回类型,因为它是泛型的。我不得不把它的类型传给工厂,这只会破坏工厂的想法那么,我如何创建一个实例化接口的泛型类型的工厂方法呢
您的问题是您的泛型并不是真正的泛型。所以你的方法不应该是通用的,因为我不能说:
GetProductDAO<int>(someEnum);
我相信从工厂中移除通用不仅可以解决问题,还可以为API用户提供更好的清晰度和一致性话虽如此,泛型确实允许更好的智能感知
我最喜欢的解决方案是删除枚举,只传递泛型类型,然后对方法添加限制。
public static IProducts<T> GetProductDAO<T>() where T: ISomeMarkerInterface, new()
所以SimpleProductDAO
将实现ISomeMarkerInterface
,它只是一个空接口:
public interface ISomeMarkerInterface
{
}
工厂变小:
public static class ProductFactory
{
public static IProducts<T> GetProductDAO<T>() where T : ISomeMarkerInterface, IProducts<T>, new()
{
return new T();
}
}
或者
将工厂定义为:
public static IProducts<T> GetProductDAO<T>(ProductEnum product)
{
...
这不是我最喜欢的解决方案,因为它可以在没有限制的情况下被滥用