📜  java observable to observer - Java (1)

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

Java Observable to Observer

Java Observable and Observer are two classes that are used to implement the observer design pattern. The observer design pattern is a pattern where an object maintains a list of its dependents, called observers, and notifies them automatically of any state changes. This pattern is used to avoid tight coupling between the classes.

Observable Class

The Observable class is an abstract class and is part of the java.util package. It provides the basic functionality for registering, unregistering and notifying observers. The Observable class is responsible for keeping track of the state of the object it represents and notifying the registered observers of any changes.

Method addObserver()

This method is used to add an observer to the set of observers for this object. The observer will be notified of any changes of the object's state.

public synchronized void addObserver(Observer o)
Method deleteObserver()

This method is used to delete an observer from the set of observers of this object.

public synchronized void deleteObserver(Observer o)
Method notifyObservers()

This method is used to update all the observers of this object. This method will call the update() method of all the registered observers.

public void notifyObservers()
Method setChanged()

This method is used to set the changed flag of this object to true.

protected synchronized void setChanged()
Observer Class

The Observer class is an interface and is part of the java.util package. It only has one method update(). This method is called whenever the observed object is changed.

Method update()

This method is called whenever the observed object is changed.

void update(Observable o, Object arg)
Example
import java.util.Observable;
import java.util.Observer;

public class Example implements Observer {

    public static void main(String[] args) {
        Example example = new Example();
        Observable observable = new Observable();
        observable.addObserver(example);
        observable.notifyObservers("Hello World");
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(arg);
    }
}

In this example, we have created an Example class that implements the Observer interface. We have then created an Observable object and added the Example object to its list of observers. Finally, we have notified the observers of the Observable object by calling the notifyObservers() method.

Since our Example object is an observer, its update() method is called when the Observable object's state changes. In this case, we have passed a string "Hello World" to the notifyObservers() method, which is then passed to the observer's update() method.

The output of this program will be "Hello World".