开发者

IRepository with Inherited Classes

In keeping with the Repository pattern of data input, I've a question in regards to using inherited classes. For instance, suppose I would have the class...

class Employee

IEmployeeRepository
{
 Add(Emp开发者_如何学编程loyee employee);
}

This works fine, nothing wrong with it so far... but now let's say I continue on..

class Manager : Employee

Okay, now let's assume that I never need to enter a manager different than an Employee? What's the best approach here? Would a scenario such as ..

IEmployeeRepository
{
 Add<T>(T employee) where T : Employee
}

Be the best approach, or do I need to abstract a different repository for each type?


If they are all employees, I would probably create an interface and constrain it to that. For example:

IEmployeeRepository
{
 Add<T>(T employee) where T : IEmployee
}


If things are being handled differently, then you should create another Repository for the new type.

If the two never have different logic (and they really shouldn't considering a Manager is still an Employee in your case), then you can re-use what you already have. You shouldn't even need to change the code (as long as Manager inherits from the Employee class):

public interface IEmployeeRepository
{
    Add(Employee employee);
}

Should work just fine.


let's assume that I never need to enter a manager different than an Employee

So you do not have an abstraction. You only have an Employee and you need a repository for that.

do I need to abstract a different repository for each type?

Yes if you have an abstraction of a few subclasses. The point is you normally do not need a repository for abstract classes only for subclasses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜