我想通過界面將模型與視圖配對。我想控制更新視圖的時間和頻率。所以像PropertyChangeListener這樣的東西不能很好地工作(在每個屬性設置後觸發一個事件)。GUI模式問題:PropertyChangeListener與專業視圖界面
我沒有爲特定的GUI框架開發。這裏的目標是能夠交換不同的GUI前端(現在用於測試,但稍後可能對不同版本的應用有用)。這些可能是Swing,或者它可能是一個Web瀏覽器(例如,通過GWT)。
下面是我的方法。該視圖實現了提供更新方法的界面。這是由控制器在確定完成更新模型時觸發的。對我來說,這仍然感覺很好,因爲Controller只通過模型與視圖進行交互,所以控制器不依賴於視圖的特定實現。
所以,我想我的問題(S)的
- 做這項工作呢?
- 這是標準做法嗎?
- 此模式是否有名字?
粗糙的代碼示例(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) {
// ...
}
}