📜  java observable - Java (1)

📅  最后修改于: 2023-12-03 15:01:31.760000             🧑  作者: Mango

Java Observable

Java Observable is a class in the Java Language Specification that allows programmers to implement the observer pattern. The observer pattern is a design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any changes to its state.

How to use Java Observable
Step 1: Define the Observer Interface

The observer interface defines the update() method that subjects call when they notify their observers of state changes.

public interface Observer {
    void update(Observable o, Object arg);
}
Step 2: Define the Subject Class

The subject class extends the java.util.Observable class and defines the methods for adding and deleting observers as well as the method for notifying observers of state changes.

public class Subject extends java.util.Observable {
    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        setChanged();
        notifyObservers();
    }
}
Step 3: Define the Observer Class

The observer class implements the Observer interface and defines the update() method that is called when the subject changes state.

public class ObserverClass implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Subject has updated: " + o + ", state: " + ((Subject) o).getState());
    }
}
Step 4: Add Observers to the Subject
public static void main(String[] args) {
    Subject subject = new Subject();
    ObserverClass observer1 = new ObserverClass();
    ObserverClass observer2 = new ObserverClass();
    
    subject.addObserver(observer1);
    subject.addObserver(observer2);
    
    subject.setState(1);
    subject.setState(2);
    subject.setState(3);
}
Conclusion

Java Observable is a powerful tool for implementing the observer pattern in Java. By following these steps, you can easily implement a robust observer system in any Java program.