Author: techfox9

Design Patterns – Observer pattern (Behavioral) basic example..

Friday, May 25th, 2007 @ 11:12 pm

This is a (simplified) example from Vince Huston’s patterns pages. The part I found really neat is the self-registration methodology of observers.. normally, I expected the Subject to have an ‘add()’ method for observers.. this is a bit different.. nice..

// ObserverEx.java   

// From Vince Huston's site..

class ObserverEx {
    public static void main(String[] args) {
        Subject subj = new Subject();
        // Self-Register observers.. nice..
        new SomeObserver( subj );
        new OtherObserver( subj );
        // Do something to the subject..
    }
}

class Subject {
    private Observer[] observers = new Observer[9];
    private int        numObs  = 0;

    public void attach( Observer o ) {
        observers[numObs++] = o;
    }

    private void notifyObservers() {
        for (int ix = 0; ix < numObs; ix++) {
            observers[ix].update();
        }
    }

}

abstract class Observer {
    protected Subject subj;
    public abstract void update();
    public Observer( Subject subj ) {
        this.subj = subj;
    }
}

class SomeObserver extends Observer {
    public SomeObserver( Subject s ) {
        super( s );
        subj.attach(this);
    }

    public void update() {
        // Update from Subject..
    }
}

class OtherObserver extends Observer {
    public OtherObserver( Subject s ) {
        super( s );
        subj.attach(this);
    }

    public void update() {
        // Update from Subject..
    }
}


Engineering, Software


 


Comments are closed.