我想优化我的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()
}
答案 0 :(得分:1)
如果我是你,我会做这样的事情:
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());
}
我希望这可以帮到你