This article describes the use of observer mode to implement the high temperature warning function of the Meteorological Bureau. Share it for your reference, as follows:
1. Pattern definition
Observer mode, also known as publish/subscribe mode. The observer pattern defines a one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.
2. Examples of the model
1 Pattern Analysis
We borrow the Meteorological Bureau’s high temperature warning to illustrate this model.
2 Observer pattern static class diagram
3 Code Examples
3.1 Observer interface-IObserver
package com.demo.observer;import com.demo.subject.ISubject;/** * Observer interface* @author * */public interface IObserver{ //Update method public void update(ISubject subject);}3.2 Topic Interface-ISubject
package com.demo.subject;import com.demo.observer.IObserver;/** * Topic interface (observer) * * @author * */public interface ISubject{ /** * Add observer* * @param observer * @return */ public boolean add(IObserver observer); /** * Delete observer* * @param observer * @return */ public boolean remove(IObserver observer); /** * Notify all observers to update data*/ public void notifyAllObserver(); /** * Set the temperature value * * @param temperature */ public void setTemperature(float temperature); /** * Get a temperature warning* * @return */ public String temperatureReport();}3.3 Implementation of a Subject in specific topics
package com.demo.subject;import java.util.Iterator;import java.util.Vector;import com.demo.observer.IObserver;/** * Theme implementation class (observer) * * @author * */public class Subject implements ISubject { // Temperature/** * (I) High temperature yellow warning signal* * Standard: The maximum daily temperature will be above 35℃ for three consecutive days. * * (2) High temperature orange warning signal* * Standard: The maximum temperature will rise to above 37℃ within 24 hours. * * (III) High temperature red warning signal* * Standard: The maximum temperature will rise to above 40℃ within 24 hours. */ private float temperature; // early warning level private String warningLevel; // save observer list private final Vector<IObserver> vector; /** * Construct method initialize observer list*/ public Subject() { vector = new Vector<IObserver>(); } /** * Add observer*/ public boolean add(IObserver observer) { if (observer != null && !vector.contains(observer)) { return vector.add(observer); } return false; } /** * Remove observer*/ public boolean remove(IObserver observer) { return vector.remove(observer); } /** * Notify all observers to update data*/ public void notifyAllObserver() { System.out.println("============ The meteorological department releases high temperature" + this.warningLevel + "Alarm!==========); Iterator<IObserver> iterator = vector.iterator(); while (iterator.hasNext()) { (iterator.next()).update(this); } } /** * Private method sets the warning level according to the temperature value and notifies all observers*/ private void invoke() { if (this.temperature >= 35) { if (this.temperature >= 35 && this.temperature < 37) { this.warningLevel = "yellow"; } else if (this.temperature >= 37 && this.temperature < 40) { this.warningLevel = "orange"; } else if (this.temperature >= 40) { this.warningLevel = "red"; } // Notify all observers of temperature status this.notifyAllObserver(); } } /** * Set the temperature value* * @param temperature */ public void setTemperature(float temperature) { this.temperature = temperature; this.invoke(); } /** * Get a temperature warning*/ public String temperatureReport() { return " Temperature:" + this.temperature; }}3.4 Personal Observer-PersonObserver
package com.demo.observer;import com.demo.subject.ISubject;/** * Individual user observer* @author * */public class PersonObserver implements IObserver{ public void update(ISubject subject) { System.out.println("Individuals receive high temperature warning: " + subject.temperatureReport()); }}3.5 Government Observer-GovernmentObserver
package com.demo.observer;import com.demo.subject.ISubject;/** * Government User Observer* @author * */public class GovernmentObserver implements IObserver{ public void update(ISubject subject) { System.out.println("Government department received a high temperature warning: " + subject.temperatureReport()); }}3.6 CompanyObserver
package com.demo.observer;import com.demo.subject.ISubject;/** * Enterprise and institutions user observer* @author * */public class CompanyObserver implements IObserver{ public void update(ISubject subject) { System.out.println("Enterprises and institutions receive high temperature warning: " + subject.temperatureReport()); }}3.7 Let the system start running a Client
package com.demo;import java.util.Random;import com.demo.observer.CompanyObserver;import com.demo.observer.GovernmentObserver;import com.demo.observer.PersonObserver;import com.demo.subject.ISubject;import com.demo.subject.Subject;/** * Client application* * @author * */public class Client { /** * @param args */ public static void main(String[] args) { // Create topic object ISubject subject = new Subject(); // Add observer of enterprise and institution subject.add(new CompanyObserver()); // Add observer of government user subject.add(new GovernmentObserver()); // Add observer of individual user subject.add(new PersonObserver()); Random random = new Random(); int i = 0; while (++i < 10) { // Set random temperature subject.setTemperature(random.nextInt(45)); } }}4 Running results
======== The meteorological department issues a yellow high temperature alarm!======
Enterprises and institutions receive high temperature warning: Temperature: 35.0
Government departments received high temperature warning: Temperature: 35.0
Individuals receive high temperature warning: Temperature: 35.0
======== The Meteorological Department issues a red alarm for high temperature!======
Enterprises and institutions receive high temperature warning: Temperature: 43.0
Government departments received high temperature warning: Temperature: 43.0
Individuals receive high temperature warning: Temperature: 43.0
======== The Meteorological Department issues a high temperature orange alarm!======
Enterprises and institutions receive high temperature warning: Temperature: 37.0
Government departments received high temperature warning: Temperature: 37.0
Individuals receive high temperature warning: Temperature: 37.0
3. The design principles of this model
1 "Open-closed" principle
2 Single Responsibility Principle
3. The principle of dependency inversion
4. Use occasions
1 When an abstract model has two aspects, one of which depends on the other, and needs to be encapsulated into independent objects and independently changed and multiplexed each other.
2 When the change of an object in a system requires changing the content of other objects at the same time, but you don’t know how many objects are to be changed.
3 When an object's change must be notified to make corresponding changes, but it is not possible to determine who the object is notified.
5. "Pull data" static class diagram
The so-called "pushing data" means that when the observed object changes, the relevant data is passed to the observer through parameters, which forms the observer "pushing data" to the observer. The static class diagram is as follows:
6. "Pull data" static class diagram
The so-called "pull data", the observer object contains a reference to the instance of the object being observed. When the object being observed changes, no data will be passed to the observer. The observer actively obtains the relevant data based on the reference of the object being observed. This forms the observer actively "pulls data" from the object being observed. The static class diagram is as follows:
For more Java-related content, readers who are interested in this site can view the topics: "Introduction and Advanced Tutorial on Java Object-Oriented Programming", "Tutorial on Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.