So that when an object's state changes, all objects that depend on it are notified and change accordingly.
There are many ways to implement the observer pattern: this pattern must include two roles: observer and object being observed. There is a logical relationship of "observation" between the observer and the observer. When the observer changes, the observer will observe such changes and issue corresponding changes.
/** * Observer interface: observer, class that needs to use observer mode needs to implement this interface*/public interface Observer{ public void update(Object obj);} /** * Observer (usually abstract class, convenient for expansion): declare method, some change has occurred, notify the observer of the change. */public interface BeenObserved{ public void addObserver(Observer obs);//add observer object public void removeObserver(Observer obs);//observer object public void notifyObservers(String changed);//notify the observer object to change correspondingly} /** * Target observer: implement the interface of the observer and perform corresponding operations on the observer object*/public class ConcreteWatched implements BeenObserved { // Observer object collection private List<Observer> list = new ArrayList<Observer>(); @Override public void addObserver(Observer obs)// Add the observer { if (!list.contains(obs)) { list.add(obs); } } @Override public void removeObserver(Observer obs)// The observer tells the observer to cancel the observation and remove the observer from the container { if (list.contains(obs)) { list.remove(obs); } } @Override public void notifyObservers(String change) { // traverse the object and call methods separately for update notification operations for (Observer obs : list) { obs.update(change); } }} /** * Targeted being observed (specific observer) */public class SpecificWatcher implements Observer{ @Override public void update(Object obj) { System.out.println(obj.toString());//changes occurring}}/** * Test code* @description: */public class Test { public static void main(String[] args) { BeenObserved bObs = new ConcreteWatched(); Observer obs1 = new SpecificWatcher(); Observer obs2 = new SpecificWatcher(); Observer obs3 = new SpecificWatcher(); bObs.addObserver(obs1);//Add observer object bObs.addObserver(obs2); bObs.addObserver(obs3); bObs.notifyObservers("***Notified***"); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Finally print the result:
The above is all about this article, I hope it will be helpful for everyone to learn Java programming.