views:

93

answers:

2

How is the Observer Pattern expressed in various programming languages? Can you provide a code snippet that illustrates the major differences in each language. This post is intended to demonstrate the differences of this commonly used design pattern.

I will start this off with a Java example. Remember to start your answer off with the language being demonstrated.

+1  A: 

Java: I am aware of the java.util.Observable, but I wanted to demonstrate an manual implementation.

interface Subject {
    void addObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObserver(Observer o);
}

class RealSubject implements Subject {
    private String property;
    private Vector<Observer> observers;

    RealSubject() {
        observers = new Vector<Observer>();
        property = "value";
    }
    public void addObserver(Observer o) {
        observers.add(o);
    }
    public void removeObserver(Observer o) {
        if (observers.indexOf(o) >=0 ) observers.remove(o);
    }
    public void notifyObserver(Observer o) {
        for (Observer obs : observers) {
            obs.update(property);
        }
    }
    public String getProperty() {
        return property;
    }   
}

interface Observer {
        void update(String property);
}

class RealObserver implements Observer {
    private String property;
    private Subject s;

    RealObserver(Subject s) {
        this.s = s;
        s.addObserver(this);
    }
    public void update(String property) {
        this.property = property;
    }

}
Shiftbit
A: 

You should look at http://en.wikipedia.org/wiki/Observer_pattern, there are some examples.

Chris