有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在MVC中将模型传递给视图

我一直认为MVC意味着模型不应该了解视图,反之亦然。然而,在我的大学课程中,使用MVC模式的视图示例如下所示:

class View implements Updatable {

    private final JButton button = new JButton("Press Me!");
    private final JTextField textField = new JTextField(10);

    //some setup of the button and textfield

    public void update(Model model) {
        if (model.morePressesAllowed()) {
            textField.setText(String.valueOf(model.count()));
        } else {
            textField.setText("Too Many!");
            button.setEnabled(false);
        }
    }
}

我觉得奇怪的是,视图必须知道模型有哪些方法。就MVC模式而言,向控制器公开按钮和文本字段,并在控制器上使用更新方法似乎更好

模型只是增加一个数字,如果它达到5,则MorePresseAllowed返回false

此外,模型有一个可更新的列表,当计数器更改时,它会在可更新的列表中循环并调用update,虽然这比使用列表视图要好,但控制器似乎仍然应该负责告诉视图模型何时更改

编辑:模型是:

class Model {
    private final List<Updatable> views = new ArrayList<Updatable>();
    private int count;
    private boolean morePressesAllowed = true;
    public void addObserver(Updatable observer) {
        views.add(observer);
    }
    public void increment() {
        count++;
        if (count >= 5) {
            morePressesAllowed = false;
        }
        notifyObservers();
    }
    private void notifyObservers() {
        for (Updatable view : views) {
            view.update(this);
        }
    }
}

控制器/主类:(控制器不应该创建模型和视图,并且是普通的公共类吗?)

public class GuiApp {
    private View view = new View(new Controller());
    private Model pressCounter = new Model();

    class Controller implements ActionListener {
        public void actionPerformed(ActionEvent actionEvent) {
            pressCounter.increment();
        }
    }
    GuiApp() {
        pressCounter.addObserver(view);
    }
}

而且我实际上更喜欢这样:http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm因为控制器只是包装了视图和模型的一系列方法,虽然看起来更像MVC,因为模型和视图彼此不了解,但它似乎效率更低,更复杂


共 (1) 个答案

  1. # 1 楼答案

    It seems like it would be better in terms of the MVC pattern to expose the button and textfield to the controller, and have the update method on the controller?

    这将在视图和控制器之间创建耦合。重要的是,每一层都尽可能少地了解彼此。您不希望控制器依赖于某些文本框或按钮的存在。您希望控制器将数据传递回视图,而不关心之后会发生什么。这就是视图的工作。这就是授权的全部意义

    Also the model has a list of Updatable, and when the counter changes it loops through the updatables and calls update, while this is better than having a list Views, it still seems like the Controller should be responsible for telling the view when the model changes?

    你说得对。视图的角色不是调用模型上的方法。同样,这会产生不希望的耦合

    also shouldn't the controller create the model and view and be normal public class?

    对。我经常看到控制器与模型层或某个服务进行通信,然后返回模型,然后将模型委托给视图

    Because in that the controller is just wrapping a bunch of methods of the view and model, which while it seems more MVC like in that the Model and View don't know anything about each other, it just seems less efficient and more complex?

    这些方法被称为代理方法。方法,它们只是将调用委托给其他对象。当您试图在体系结构中保持适当的关注点分离时,这很有帮助。这取决于你对复杂事物的定义。是的,它为控制器添加了更多方法。同样,当下一个开发人员出现时,如果他或她能够安全地假设您的应用程序严格遵循MVC体系结构,他们将更容易根据您的代码进行开发,而不是必须进行微优化和“变通”