0

Let's assume I have a User class and two subclasses Employee and Customer. I implemented this hierarchy as a table-per-hierarchy in DB with a column for specifying the type of user. I need to return the right type of object when querying this table.

Do I need separate DAOs for each type of object like CustomerDAO or EmployeeDAO, so each return their respective Customer and Employee objects. If so how to get them from DAOFactory without using:

if(type.equlas('customer'))
    return customerDao;
else
    retrun employeeDao;

Because the types implementing User could change and I don't want to change conditions every time.

Or is there any other way? Any idea would be appreciated.

Note: I'm not using any ORM framework and not planning to use one.

4

1 回答 1

0

如果每种类型的持久性代码相同,那么您可以拥有 1 个通用 DAO。

所以你的用户 dao,可能是这样的:

interface DAO<T, ID> {
  T create(T t);
  T read(ID id);
  T update(T t);
  void delete(T t);  
}

class UserDAO<T extends User> implements DAO<T> {
    // Your methods for crud operations will be limited to types of User.
}

然后你的工厂类可以简单地通过指定正确的类型来实例化正确的 DAO。

class DAOFactory {
  public UserDAO<Employee> getEmployeeDAO() {
    return new UserDAO<Employee> ();
  }
}

问候
优素福

于 2011-07-08T23:17:20.863 回答