将应用程序转换为 MVC 并在控制台和 GUI 中运行它
我有一个简单的 java gui 计算器,有 3 个数字系统(有一些错误,但现在不重要了)。目前所有代码都在一个文件中。我的任务是将其重写为 MVC,并添加在 gui 或控制台模式下运行它的可能性。我应该如何划分这个程序以将其组织为 MVC?它的编写是否足够正确,可以向其中添加控制台功能? (我猜我必须将调用 JLabel Output 的所有方法更改为简单地将输出字符串存储为模型参数,然后让 View 获取它)。
这是起始代码:
http://paste.pocoo.org/show/224566/
这是我已经拥有的:
主要:
http://paste.pocoo.org/show/224567/
型号:
http://paste.pocoo.org/show/224570/
查看:
http://paste.pocoo.org/show/224569/
控制器:
http://paste.pocoo.org/show/224568/
我没有在我的模型中查看,因此我无法调用输出。这是我看到的第一个问题。
I have a simple java gui calculator, with 3 number systems (there are some bugs but that doesn't matter now). Currently all code is in one file. My task is to rewrite it as MVC, and add possibility to run it in either gui or console mode. How should I divide this program to organise it as M-V-C ? Is it written properly enough to add console functionality to it? (guess I'll have to change all methods invoking to JLabel Output to something simply storing an output String as a model argument and then having View to get it).
Here's the starting code :
http://paste.pocoo.org/show/224566/
Here's what I already have :
Main :
http://paste.pocoo.org/show/224567/
Model :
http://paste.pocoo.org/show/224570/
View :
http://paste.pocoo.org/show/224569/
Controller :
http://paste.pocoo.org/show/224568/
I don't have view in my model so I can't call to Output. That's the first problem I can see.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前的分离看起来不错。以下是实现控制台视图的一些提示:
Action
类。然后视图调用该操作来响应 UI 手势。这使控制器独立于视图实现,并允许多个视图使用同一个控制器。然后,控制台视图可以读取标准输入,通过查询模型将状态写入标准输出,并使用控制器公开的操作调用函数。
MVC 的一个很好的测试是在同一模型和控制器上创建两个视图 - 两者都应该正常工作并根据对方的更改进行更新。
The current separation looks good. Here are some pointers for implementing the console view:
Action
class. The view then invokes the action in response to UI gestures. This keeps the controller independent of the view implementation, and allows the same controller to be used by multiple views.The Console View can then read standard input, and write status to standard output by querying the model, and invoke functions using the Actions exposed by the controller.
A good test of MVC is creating two views on the same model and controller - both should work correctly and update from changes from the other.
您应该熟悉观察者模式。这种模式将允许您的模型随时更改,但不需要知道不同的视图(这正是我们正在寻找的)。
简而言之,模型会说:“嘿,我已经改变了。任何有兴趣的人都应该采取相应的行动”。
You should get familiar with the Observer pattern. This pattern will allow your model to change any time, but without the need to know the different views (which is what we are looking for).
Simply put, the model will say: "Hey, I've changed. Anyone who is interested should act accordingly".