【发布时间】:2009-04-11 14:32:50
【问题描述】:
我想通过界面将模型与它的视图配对。我想控制视图更新的时间和频率。所以像 PropertyChangeListener 这样的东西不能很好地工作(在设置每个属性后触发一个事件)。
我不是为特定的 GUI 框架开发的。这里的目标是能够交换不同的 GUI 前端(现在用于测试,但以后可能对不同版本的应用程序有用)。这些可能是 Swing,也可能是 Web 浏览器(例如,通过 GWT)。
以下是我的方法。视图实现了一个接口来提供更新的方法。这由控制器在确定模型更新完成时触发。这对我来说仍然没问题,因为控制器只是通过模型与视图交互,控制器不依赖于视图的特定实现。
所以,我想我的问题是
- 这行得通吗?
- 这是标准做法吗?
- 这个模式有名字吗?
粗略的代码示例(Java):
// Controller, manages Items (the model)
class ItemList {
void addItem(Item item) {
}
void doStuffWithItems() {
// perform some set of operations, such as sorting or layout
for (Item item : items) {
// ....
}
// now with everything in it's final position:
for (Item item : items) {
item.updateView();
}
}
}
// Model
class Item {
private int top;
private int left;
private int width;
private int height;
// Can remember it's previous position/size:
public void savePostion() {
}
// And recall it for the Controller to use:
public public Position getSavedPosition() {
}
// Plus some other useful functions:
public boolean intersectsWith(Item other) {
}
public void updateView() {
this.view.update();
}
void setView(ItemView view) {
this.view = view;
}
}
// Interface used by View implementations
public interface ItemView {
// Trigger the view to reflect the current state of the model
void update();
}
// Example, as a Swing component
class ItemComponent extends JComponent implements ItemView {
private Item item;
public ItemComponent(Item item) {
this.item = item;
item.setView(this);
}
// ItemView#update
public void update() {
// update the component's size/position
setBounds(new Rectangle(item.getLeft(), item.getTop(), item.getWidth(), item.getHeight()));
}
@Override
public void paint(Graphics g) {
// ...
}
}
【问题讨论】:
标签: user-interface language-agnostic design-patterns