Chapter 18: The Observer Pattern
Code Examples
TOC
The Observer pattern aids flexibility and keeps things decoupled
Example 18-1: Observer Implemented
TOP
// Note: I don't use the Java Observer or Observable.
// In practice they give me little assistance and I
// don't like their interfaces.
import java.util.*;
public class Customer {
private static Vector myObs;
static {
myObs= new Vector();
}
public static void attach(MyObserver o){
myObs.addElement(o);
}
public static void detach(MyObserver o){
myObs.remove(o);
}
public String getState () {
// have other methods that will give the
// required information
// Here, just return null so this will compile
return null;
}
public void notifyObs () {
// set arg to something that helps
// tell the Observers what happened
for (Enumeration e = myObs.elements(); e.hasMoreElements() ;) {
((MyObserver) e).update(this);
}
}
}
interface MyObserver {
void update (Customer myCust);
}
class AddrVerification implements MyObserver {
public AddrVerification () {
}
public void update (Customer myCust) {
// do Address verification stuff here
// can get more information about customer
// in question by using myCust
}
}
class WelcomeLetter implements MyObserver {
public WelcomeLetter () {
}
public void update (Customer myCust) {
// do Welcome Letter stuff
// here can get more
// information about customer
// in question by using myCust
}
}