Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.
OTExample Observer/ObserverPattern
< OTExample Observer
Revision as of 07:15, 23 February 2010 by Stephan.cs.tu-berlin.de (Talk | contribs) (New page: <source lang="otj" line="1"> package protocol; import java.util.LinkedList; /** * This team gives a reusable implementation of the Observer Pattern. * Only application-specific parts ...)
package protocol;
import java.util.LinkedList;
/**
* This team gives a reusable implementation of the Observer Pattern.
* Only application-specific parts are left abstract.
*/
public abstract team class ObserverPattern {
/**
* The Subject role of the observer pattern.
* Abstractness is not strictly needed, but it signals that applications
* of the pattern should refine this role.
*/
protected abstract class Subject {
/** Registry of known Observers: */
private LinkedList<Observer> observers = new LinkedList<Observer>();
public void addObserver (Observer o) {
observers.add(o);
}
public void removeObserver (Observer o) {
observers.remove(o);
}
public void removeAllObservers() {
observers.removeAll(observers);
}
/**
* All edit operations of the concrete Subject should call into this method.
*/
public void changeOp() {
for (Observer observer : observers)
observer.update(this);
}
/**
* Variant for multiple changes in one method call.
* Because we suspect reentrance at the base side, we temporarily deactivate this Team.
* (This solves the problem known as "jumping aspects"
* where more notifications would be sent than needed).
* By declaring the method as "callin" it is designed to be bound using "replace".
*/
callin void changeOpMany () {
boolean wasActive = isActive();
deactivate(); // no notification during the base call.
base.changeOpMany(); // call original version (requires "callin" modifier).
if (wasActive)
activate(); // restore state
changeOp();
}
}
/**
* Observer role of the design pattern.
*/
protected abstract class Observer {
/**
* This method needs to be realized to do something usefull
* on the actual observer instance.
*/
abstract void update(Subject s);
/**
* To be called, when a concrete observer starts to participate in the pattern.
* @param s the subject to connect to.
*/
public void start (Subject s) {
s.addObserver(this);
}
/**
* To be called, when a concrete observer stops to participate in the pattern.
* @param s the subject to disconnect from.
*/
public void stop (Subject s) {
s.removeObserver(this);
}
}
}