我发现自己需要覆盖静态方法,仅仅因为它最有意义,但我也知道这是不可能的.
超类Entity.java:
abstract public class Entity<T> {
public Entity() {
//set up database connection
}
abstract public static Map<Object, T> getAll();
abstract public void insert();
abstract public void update();
protected void getData(final String query) {
//get data via database
}
protected void executeQuery(final String query) {
//execute sql query on database
}
}
Account.java的许多具体实现之一:
public class Account extends Entity<Account> {
private final static String ALL_QUERY = "SELECT * FROM accounts";
private final static String INSERT_QUERY = "INSERT INTO accounts (username, password) VALUES(?, ?)";
private final static String UPDATE_QUERY = "UPDATE accounts SET password=? WHERE username=?";
private String username;
private String password;
public Account(final String username, final String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
@Override
public static Map<Object, Account> getAll() {
//return a map using the ALL_QUERY string, calls getData(string);
}
@Override
public void insert() {
//insert this using INSERT_QUERY, calls executeQuery(string);
}
@Override
public void update() {
//update this using UPDATE_QUERY, calls executeQuery(string);
}
}
我没有深入解释代码,但是对它的任何一般反馈也将不胜感激,我希望这些评论足够解释.
所以基本上我认为我们都同意使用Account.getAll()对新的Account()更有意义.getAll()(如果我要为它引入一个虚拟语法).
但是我确实希望它扩展Entity类,目前它只是为了方便,但后来我可能必须使用Entity的sets / lists / multisets并对所有这些执行update()动作,例如,如果我会建立一些每分钟都能完成所有更新的队列.
那么,有没有办法正确构造getAll()?
问候.
最佳答案 您可以在所有元素上有单独的操作类:
abstract public class Collection<T extends Entity<T>> {
abstract public static List<T> getAll();
public void printAll() {
// Print all entries of List obtained from getAll()
}
}
你可以用作:
public class Accounts extends Collection<Account> {
@Override
public List<Account> getAll() {
//return a list using the ALL_QUERY string, calls getData(string);
}
}