到目前为止,我已经实现了一个基于 Swing 的 GUI,并根据 MVC 模式(如(此处)),其中事件从视图(通过使用 JComponents 功能)和模型(通过使用 PropertyChangeSupport bean)触发。控制器在中间,监听它们并转发事件,如下:
看法
public class GUIview extends JFrame {
public void propertyChange(final PropertyChangeEvent event) {
if (event.getPropertyName().equals(GUIcontroller.A1_PROPERTY)) {
method_a1(event.getNewValue());
} else if (event.getPropertyName().equals(GUIcontroller.A2_PROPERTY)) {
method_a2(event.getNewValue());
}
}
public void method_a1() {...}
public void method_a2() {...}
}
控制器
public class GUIcontroller implements PropertyChangeListener {
public static final String A1_PROPERTY = "a1";
public static final String A2_PROPERTY = "a2";
public static final String B1_PROPERTY = "b1";
public static final String B2_PROPERTY = "b2";
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().charAt(0) == 'a') {
GUIview.propertyChange(event);
} else if (event.getPropertyName().charAt(0) == 'b') {
GUImodel.propertyChange(event);
}
}
}
模型
public class GUImodel {
public PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
propertyChangeSupport.firePropertyChange(propertyName, oldValue,
newValue);
}
public void propertyChange(final PropertyChangeEvent event) {
if (event.getPropertyName().equals(GUIcontroller.B1_PROPERTY)) {
method_b1(event.getNewValue());
} else if (event.getPropertyName().equals(GUIcontroller.B2_PROPERTY)) {
method_b2(event.getNewValue());
}
}
public void method_b1() {...}
public void method_b2() {...}
}
现在它可以工作了,但据我所知(或据我所知),视图应该只包含布局功能,所有工作都必须由控制器和模型完成。另一方面,控制器应尽可能薄。
我找不到在视图和模型上实现 propertyChange() 方法的理由,并从那里进行方法调用,而不是直接从控制器调用这些方法,如下所示:
public class GUIcontroller implements PropertyChangeListener {
public static final String A1_PROPERTY = "a1";
public static final String A2_PROPERTY = "a2";
public static final String B1_PROPERTY = "b1";
public static final String B2_PROPERTY = "b2";
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals(GUIcontroller.A1_PROPERTY)) {
GUIview.method_a1(event.getNewValue());
} else if (event.getPropertyName().equals(GUIcontroller.A2_PROPERTY)) {
GUIview.method_a2(event.getNewValue());
} else if (event.getPropertyName().equals(GUIcontroller.B1_PROPERTY)) {
GUImodel.method_b1(event.getNewValue());
} else if (event.getPropertyName().equals(GUIcontroller.B2_PROPERTY)) {
GUImodel.method_b2(event.getNewValue());
}
}
}
考虑到这两种方法,哪一种更接近真正的 MVC 模式?
哪个可能是在视图和模型上实现propertyChange()方法的主要原因?