在 DAO 模式中使用泛型
Using Generics in DAO Pattern
// Domain Class
public class Actor {
private int id;
private String firstName;
private String lastName;
private Date lastUpdate;
// getters and setters
}
// DAO Interface
public interface IDao<T> {
void save(T t);
}
// Concrete Class
public class ActorDao implements IDao {
@Override
public void save(Actor actor) {
// Error: The method save(Actor) of type ActorDao must override or implement a supertype method
}
}
当 IDao
的参数为 T
时,为什么覆盖 save()
不接受 Actor
?
您需要指定 class T 是什么,如下所示:
public class ActorDao implements IDao<Actor> {
// Domain Class
public class Actor {
private int id;
private String firstName;
private String lastName;
private Date lastUpdate;
// getters and setters
}
// DAO Interface
public interface IDao<T> {
void save(T t);
}
// Concrete Class
public class ActorDao implements IDao {
@Override
public void save(Actor actor) {
// Error: The method save(Actor) of type ActorDao must override or implement a supertype method
}
}
当 IDao
的参数为 T
时,为什么覆盖 save()
不接受 Actor
?
您需要指定 class T 是什么,如下所示:
public class ActorDao implements IDao<Actor> {