我想优化Java编程代码,以更好地分离模型和视图。
目前,我有代表视图的面板和代表模型的POJO和DAO。
是否可以将模型组件DaoUser与“查看面板”分开?
// Panel User
class UserPanel extends JPanel{
DaoUser daoUser = new DaoUser;
User user = daoUser.findUser(current_id);
JTextField tf = new JTextField();
tf.setText(user.getName());
}
//POJO User
class User{
int id;
String name;
Getters and Setters ..
}
// Dao User
class DaoUser{
public void saveUser(User user)
public User findUsers();
public List<User> listUsers()
}
最佳答案
如果我是你,我会做这样的事情:
class DaoUser extends Observable {
//other methods
public User findUsers (int id_user) {
//find your user. Once you find it
setChanged();
notifyObservers(user_found);
}
}
并且您认为应该执行以下操作:
class UserPanel extends JPanel implements Observer {
tf = new JTextField();
}
@Override
public void update(Observable o, Object ob) {
User u=(User) ob;
tf.setText(u.getName());
}
希望对您有帮助