假设您将有一个帖子,每个视图都有多个评论,您应该设置它,以便模型包含帖子及其所有评论。然后视图将确定如何显示帖子。这样,如果您想拥有不同的布局,您可以为同一模型拥有多个视图。每个视图都可以决定以不同的方式显示帖子,但模型不需要更改。
控制器将处理视图和模型之间的任何操作。视图不应直接修改模型。相反,视图定义了用户如何与底层数据交互,将其传递给控制器,然后控制器修改模型。这样,如果您有两个具有相同模型的视图,它们可以独立运行并且仍然获得相同的更新。
我喜欢让我所有的模型都扩展这个类。它只是让我不必每次都为听众编写代码。
import javax.swing.event.EventListenerList;
/**
* AbstractModel - Base class for a Model in a MVC pattern. This class contains
* an EventListenerList to allow for notification of a view that it's model has
* changed.
*/
public abstract class AbstractModel {
private final EventListenerList observers = new EventListenerList();
/**
* Constructor
*/
protected AbstractModel() {
}
/**
* Add a ModelChangeListener
*
* @param listener
*/
public void addModelChangedListener(final ModelChangedListener listener) {
observers.add(ModelChangedListener.class, listener);
}
/**
* Notifies listeners that the model has changed. Use the event property
* name to determine what has changed
*
* @param event
*/
protected void fireModelChangedEvent(final ModelChangedEvent event) {
for (final ModelChangedListener l : observers
.getListeners(ModelChangedListener.class)) {
l.modelChanged(event);
}
}
/**
* Remove a ModelChangeListener
*
* @param listener
*/
public void removeModelChangedListener(final ModelChangedListener listener) {
observers.remove(ModelChangedListener.class, listener);
}
}
import java.beans.PropertyChangeEvent;
/**
* ModelChangedEvent - An event used when a view's model has changed.
*
*/
public class ModelChangedEvent extends PropertyChangeEvent {
/**
* Constructor
*
* @param source
* @param propertyName
* @param oldValue
* @param newValue
*/
public ModelChangedEvent(final Object source, final String propertyName,
final Object oldValue, final Object newValue) {
super(source, propertyName, oldValue, newValue);
}
}
import java.util.EventListener;
/**
* Interface for classes interested in ModelChangedEvents. Intended to be used
* by view classes in a MVC pattern.
*/
public interface ModelChangedListener extends EventListener {
/**
* Notifies this Listener that the model has changed.
*
* @param event
*/
public void modelChanged(ModelChangedEvent event);
}