PlanetXML

Das Beobachter Muster

Implementierung und Test des Beobachter Musters, erstellt am 9.11.2003

import java.io.*;
import java.util.*;

abstract class Subject
{
    private Vector observers = null;

    public Subject()
    {
        observers = new Vector();
    }

    public void attach(Observer o)
    {
        observers.addElement(o);
    }

    public void detach(Observer o)
    {
        observers.removeElement(o);
    }

    public void notifyObserver()
    {
        for (Enumeration i=observers.elements(); i.hasMoreElements(); ) {
             Observer o = (Observer)i.nextElement();
             o.update();
        }
    }
}

abstract class Observer
{
    abstract public void update();
}

class ConcreteSubject extends Subject
{
    private int state = 0;

    public int getState()
    {
        return state;
    }

    public void setState(int state)
    {
        this.state = state;
        System.out.println("State changed to " + state);
        notifyObserver();
    }
}

class ConcreteObserver extends Observer
{
    private String          name    = null;
    private ConcreteSubject subject = null;

    public ConcreteObserver(String name,ConcreteSubject subject)
    {
        this.name    = name;
        this.subject = subject;
    }

    public void update()
    {
        int state = subject.getState();
        System.out.println("Update : " + name + " : " + state);
    }
}

public class Main
{
    public static void main(String args[])
    {
        ConcreteSubject  s  = new ConcreteSubject();
        ConcreteObserver o1 = new ConcreteObserver("O1",s);
        ConcreteObserver o2 = new ConcreteObserver("O2",s);
        ConcreteObserver o3 = new ConcreteObserver("O3",s);

        s.attach(o1);
        s.attach(o2);
        s.setState(0);
        System.out.println();

        s.attach(o3);
        s.setState(1);
        System.out.println();

        s.detach(o1);
        s.setState(2);
        System.out.println();
    }
}