我有一个界面
interface IRepository<T>
{
List<T> GetAll(string id)
List<T> GetAll(string id, string desc)
List<T> GetAll(string id, string desc, int[] status)
List<T> GetAll(string id, string desc, int[] status, ....)
}
我的很多课程都在实现这个界面。我的问题是,更常见的情况是,当客户端请求自定义时,我通常需要在方法上添加参数。所以当我有10个类实现这个接口时,我还需要更新继承接口的每个类(我使用的是抽象工厂模式),这非常麻烦。并且它也不是很令人愉快,因为看到许多方法重载,如上面的例子,imo。是否有任何解决方案/解决方法使参数动态(除了我不喜欢的param []选项)。我的意思是像一个专用的类/接口参数,所以当我添加参数时,我不需要重载该方法。这样的东西
interface IRepository<T>
{
List<T> GetAll(Parameter args);
}
Paramter类(或可能是接口)
static class Parameter
{
public string Id { get; set; }
public string Desc { get; set; }
public int[] Status { get; set; }
}
客户的示例实施
class Client1Accounts : IRepository<Employee>
{
List<Employee> GetALl(Parameter param)
{
return DataFactory.GetAllById(param.Id);
}
}
class Client2Accounts : IRepository<Employee>
{
List<Employee> GetALl(Parameter param)
{
return DataFactory.GetAllByDesc(param.Desc);
}
}
class Client2Accounts : IRepository<Employee>
{
List<Employee> GetALl(Parameter param)
{
int[] status = { 99, 88 }
return DataFactory.GetAllFiltered(param.Id, param.Desc, status);
}
}
这样,当我需要添加参数时,我只需要在参数类中添加另一个属性
static class Parameter
{
public string Id { get; set; }
public string Desc { get; set; }
public int[] Status { get; set; }
public long newLongParam { get; set; }
}
这种做法是否正确?还有其他想法吗?
答案 0 :(得分:1)
我觉得,如果他们只使用参数的 part 而忽略了其余部分,那么存储库就不会真正以完整的精神实现界面。在一些有意义的案例中,但在这种情况下它看起来不像。
接口的要点是调用者不需要关心实现是什么 - 它可以以相同的方式处理每个实现。
如果给定Client1Accounts
的实例,如果他们试图通过描述进行搜索,那么看起来像调用者会非常困惑,例如,只是为了找到完全忽略的描述。
如果不同的呼叫者确实需要搜索不同的东西,那么单一界面真的能给你带来多少价值吗?
“为参数引入一种新类型”的想法本身很好 - 但我认为,当应用于这种设计时,从长远来看它会咬你。
(如果你对“引入新类型”模式感兴趣,那么框架中有一些例子 - ProcessStartInfo
可能是我能想到的最好的模式。)
答案 1 :(得分:0)
这个怎么样:
public interface IRepository<T>
{
IQueryable<T> GetAll();
}