觀察者模式(Observer)定義:多個對象同時監聽某個主題對象,如果主題對象的屬性發生變化,會通知所有觀察者,使它們進行相應的操作。 根據這個定義,流程設計器中的模型和控制器的關係,就是觀察者模式的典型應用,一個模型對應多個控制器,而這些控制器都監聽模型屬性的變化,如果模型屬性發生變化了,就通知該模型的所有控制器,讓它們重新整理該模型對應的視圖。 舉例:模型(AbstractActivity),對應的控制器(AbstractActivityEditPart, AbstractActivityTreeEditPart),這兩個控制器在生效時,把自己作為監聽器註冊到模型(AbstractActivity)中,
public
void activate() {
if (!isActive()) {
super.activate(); ((ModelElement)
getModel()).addPropertyChangeListener(
this
); }}當模型屬性(例如座標)發生變化時,它會通知所有的控制器,
public
void setLocation(Point newLocation) {
if (newLocation ==
null) {
throw
new IllegalArgumentException(); } location.setLocation(newLocation);
firePropertyChange(
LOCATION_PROP
,
null
,
location
); }控制就會根據相應的屬性,來重新整理視圖,
public
void propertyChange(PropertyChangeEvent evt) { String prop = evt.getPropertyName();
if(AbstractActivity.
SIZE_PROP.equals(prop) ||AbstractActivity.
LOCATION_PROP.equals(prop)){ refreshVisuals(); }
else
if(AbstractActivity.
SOURCE_TRANSITIONS_PROP.equals(prop)){ refreshSourceConnections(); }
else
if(AbstractActivity.
TARGET_TRANSITIONS_PROP.equals(prop)){ refreshTargetConnections(); } }類圖如下: