The opening

The observer pattern is defined as having multiple objects watching an object, and if the state of the object changes, other dependent objects are notified, and each object acts accordingly.

The observer mode involves two concepts (the observer and the observed). The observed can only have one, and multiple objects can be used to observe the observer. One-to-many Defines a one-to-many dependency between objects. When an object’s state changes, all objects that depend on it are notified and automatically updated.


Demo in observer mode

The observed

  • 1. The observed maintains a list object of observers and an interface for registering observers.
  • 2. When the event changes, the list of all observers is traversed and the event is triggered.
  • 3. Observers implement a unified interface for event notification.
Public interface Observerable {public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObserver(); } /** * The Observerable interface is implemented. * */ implements Observerable {public class WechatServer implements Observerable {// Private List<Observer> List; private String message; public WechatServer() { list = new ArrayList<Observer>(); } @Override public void registerObserver(Observer o) { list.add(o); } @Override public void removeObserver(Observer o) { if(! list.isEmpty()) list.remove(o); @override public void notifyObserver() {for(int I = 0; i < list.size(); i++) { Observer oserver = list.get(i); oserver.update(message); } } public void setInfomation(String s) { this.message = s; System.out.println(" 新 信 息 : "+ s); NotifyObserver (); // notifyObserver(); }}Copy the code


The observer

  • 1. Observers need to define a unified interface for handling event notifications.
/*** * Abstract observers * defines an update() method, which is called back when observers call notifyObservers(). * */ public interface Observer { public void update(String message); ** / public class User implements Observer {private String name; private String message; public User(String name) { this.name = name; } @Override public void update(String message) { this.message = message; read(); } public void read() {system.out.println (name + "received message:" + message); }}Copy the code


The validation test

package com.jstao.observer; public class Test { public static void main(String[] args) { WechatServer server = new WechatServer(); Observer userZhang = new User("ZhangSan"); Observer userLi = new User("LiSi"); Observer userWang = new User("WangWu"); server.registerObserver(userZhang); server.registerObserver(userLi); server.registerObserver(userWang); Server.setinfomation ("PHP is the best language in the world!" ); System.out.println("----------------------------------------------"); server.removeObserver(userZhang); Server.setinfomation ("JAVA is the best language in the world!" ); }}Copy the code


The Observer pattern implemented by Tomcat

The observer

  • 1. The observer implements the unified interface LifecycleListener and implements the specific method lifecycleEvent.
  • 2. The observer EventObject inherits the EventObject class.
  • 3. The specific implementation of the Observer takes HostConfig as an example to implement the specific lifecycleEvent method.
public final class LifecycleEvent extends EventObject { private static final long serialVersionUID = 1L; public LifecycleEvent(Lifecycle lifecycle, String type, Object data) { super(lifecycle); this.type = type; this.data = data; } private final Object data; private final String type; public Object getData() { return data; } public Lifecycle getLifecycle() { return (Lifecycle) getSource(); } public String getType() { return this.type; } } public interface LifecycleListener { public void lifecycleEvent(LifecycleEvent event); } public class HostConfig implements LifecycleListener { public void lifecycleEvent(LifecycleEvent event) { try { host =  (Host) event.getLifecycle(); if (host instanceof StandardHost) { setCopyXML(((StandardHost) host).isCopyXML()); setDeployXML(((StandardHost) host).isDeployXML()); setUnpackWARs(((StandardHost) host).isUnpackWARs()); setContextClass(((StandardHost) host).getContextClass()); } } catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; } if (event.getType().equals(Lifecycle.PERIODIC_EVENT)) { check(); } else if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) { beforeStart(); } else if (event.getType().equals(Lifecycle.START_EVENT)) { start(); } else if (event.getType().equals(Lifecycle.STOP_EVENT)) { stop(); }}}Copy the code

The observed

  • Lifecycle, addLifecycleListener and removeLifecycleListener methods will be implemented.
  • 2. LifecycleBase implements the observed function and provides List lifecycleListeners to save the observed.
  • 3. The implementation of the container inherits the LifecycleBase class, so it naturally includes the observed functionality.
package org.apache.catalina; public interface Lifecycle { public void addLifecycleListener(LifecycleListener listener); public LifecycleListener[] findLifecycleListeners(); public void removeLifecycleListener(LifecycleListener listener); } public abstract class LifecycleBase implements Lifecycle { private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>(); private volatile LifecycleState state = LifecycleState.NEW; public void addLifecycleListener(LifecycleListener listener) { lifecycleListeners.add(listener); } public LifecycleListener[] findLifecycleListeners() { return lifecycleListeners.toArray(new LifecycleListener[0]); } public void removeLifecycleListener(LifecycleListener listener) { lifecycleListeners.remove(listener); } protected void fireLifecycleEvent(String type, Object data) { LifecycleEvent event = new LifecycleEvent(this, type, data); for (LifecycleListener listener : lifecycleListeners) { listener.lifecycleEvent(event); }}}Copy the code


Refer to the article

  • JAVA Design pattern observer pattern