正确的模型-视图-控制器设计 [英] Proper model-view-controller design

查看:39
本文介绍了正确的模型-视图-控制器设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java 项目,我正在尝试使用模型-视图-控制器设计来实现该项目.我已经建立了所有组件的主干.我在决定如何将它们连接在一起时遇到了一些麻烦,尤其是视图和控制器.

I have a Java project that I'm trying to implement with a model-view-controller design. I have the backbone of all of the components established. I'm having some trouble deciding on how to connect it all together, particularly the view and the controller.

我有一个名为 MainView 的类,它扩展了 JFrame.我有各种其他类来帮助组成 MainView,每个类都扩展 JPanel.例如,这些类之一称为ParameterView.我应该允许控制器查看这些子视图"中的每一个,还是应该让控制器只查看 MainView 并通过那里管理所有内容?

I have a class called MainView that extends JFrame. I have various other classes that help make up the MainView each of which extends JPanel. As an example one of these classes is called ParameterView. Should I allow the controller to see each of these "sub-views" or should I let the controller only see MainView and have everything be managed through there?

与模型一样,是否应该通过一个总体类来管理模型?

Likewise with the model, should the model be managed through one overarching class?

谢谢!

推荐答案

在 GUI(类 Swing)应用程序的上下文中,模型-视图-控制器与其说是具体设计,不如说是一个模糊的建议.这种模式"的变体数量惊人,没有一个合适的"变体是您应该瞄准的.您可以选择似乎能满足您当前需求的任一变体(并且可以随着您的应用的发展随时更改它).

In the context of GUI (Swing-like) application, the Model-View-Controller is more of a vague suggestion than a concrete design. The number of variants of this "pattern" is staggering and there is no one "proper" variant you should aim at. You can choose either variant that seems to support your current need (and feel free to change it as your app evolves).

也就是说,这里有一些关于您所描述情况的提示

That said, here are some pointers regarding the situation you're describing

  • 您可以使用发布/订阅机制(又名:观察者模式)或责任链模式将模型(或其部分)与视图的不同部分分离.
  • 封装视图所有部分的外观类 (MainView) 似乎是上帝类"的秘诀:一个几乎需要随着应用程序中的任何更改而更改的类(反模式).通过公开视图的不同部分,您将能够更轻松地在新上下文中重用它们.
  • 最后,通过子类化 Swing 组件来实现模型似乎不是一个好主意.这样的设计很难测试,这意味着它也非常僵硬.更喜欢委托而不是继承.或者正如 JBrains 所说:停止子类化,否则小猫会得到它".仅将继承用于覆盖 Swing 方法.立即将所有逻辑委托给与 Swing 完全隔离的对象.这将促进可测试性和未来的灵活性.

这篇关于正确的模型-视图-控制器设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆