java与mvc_java – MVC模式和Swing

我强烈推荐给你的摇摆MVC的书是Freeman和Freeman的“Head First Design Patterns”.他们对MVC有非常全面的解释.

Brief Summary

You’re the user–you interact with the view. The view is your window to the model. When you do something to the view (like click the

Play button) then the view tells the controller what you did. It’s the

controller’s job to handle that.

The controller asks the model to change its state. The controller takes your actions and interprets them. If you click on a

button, it’s the controller’s job to figure out what that means and

how the model should be manipulated based on that action.

The controller may also ask the view to change. When the controller receives an action from the view, it may need to tell the

view to change as a result. For example, the controller could enable

or disable certain buttons or menu items in the interface.

The model notifies the view when its state has changed. When something changes in the model, based either on some action you took

(like clicking a button) or some other internal change (like the next

song in the playlist has started), the model notifies the view that

its state has changed.

The view asks the model for state. The view gets the state it displays directly from the model. For instance, when the model

notifies the view that a new song has started playing, the view

requests the song name from the model and displays it. The view might

also ask the model for state as the result of the controller

requesting some change in the view.

Source(如果你想知道什么是“奶油控制器”,想想一个奥利奥饼干,控制器是奶油中心,视图是顶部饼干,模型是底部饼干.)

嗯,如果你感兴趣的话,你可以从here下载一首关于MVC模式的相当有趣的歌!

Swing编程可能遇到的一个问题涉及将SwingWorker和EventDispatch线程与MVC模式合并.根据您的程序,您的视图或控制器可能必须扩展SwingWorker并覆盖放置资源密集型逻辑的doInBackground()方法.这可以很容易地与典型的MVC模式融合,并且是Swing应用程序的典型特征.

编辑#1:

此外,将MVC视为各种模式的复合是很重要的.例如,您的模型可以使用Observer模式实现(需要将View注册为模型的观察者),而您的控制器可能使用策略模式.

编辑#2:

我还想特别回答你的问题.您应该在View中显示表按钮等,这显然会实现ActionListener.在actionPerformed()方法中,您检测事件并将其发送到控制器中的相关方法(请记住 – 视图包含对控制器的引用).因此,当单击按钮时,视图检测到事件,发送到控制器的方法,控制器可能会直接要求视图禁用按钮等.接下来,控制器将与模型交互并修改模型(其中大部分将具有getter和setter方法,以及一些其他方法来注册和通知观察者等等).一旦模型被修改,它将调用已注册观察者的更新(这将是您的情况下的视图).因此,视图现在将自行更新.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值