6.22. Observer mode

发布时间 :2025-10-25 12:24:47 UTC      

The Observer pattern (Observer Pattern) is used when there is an one-to-many relationship between objects. For example, when an object is modified, objects that depend on it are automatically notified. The observer model belongs to the behavioral model.

6.22.1. Introduction

意图: Define an one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and updated automatically.

主要解决: The problem of notifying other objects of a change in the state of one object, and taking into account ease of use and low coupling to ensure a high degree of collaboration.

何时使用: The state of an object (target object) changes, and all dependent objects (observer objects) will be notified for broadcast notification.

如何解决: Using object-oriented technology, this dependency can be weakened.

关键代码: In the abstract class there is an ArrayList for observers.

应用实例: 1. During the auction, the auctioneer observes the highest bid and then notifies other bidders of the bid. 2. In the Journey to the West, Wukong asked the Bodhisattva to surrender the Red Bodhisattva. The Bodhisattva sprinkled water to attract an old tortoise. The tortoise was the observer. He observed the Bodhisattva’s act of sprinkling water.

优点: 1. The observer and the observed are abstract and coupled. 2. Establish a set of trigger mechanism.

缺点: 1. If an observed object has many direct and indirect observers, it will take a lot of time to notify all the observers. 2. If there is a circular dependency between the observer and the observation target, the observation target will trigger a circular call between them, which may cause the system to crash. 3. The observer model has no corresponding mechanism to let the observer know how the observed object has changed, but only knows that the observed object has changed.

使用场景:

  • An abstract model has two aspects, one of which depends on the other. Encapsulate these aspects in separate objects so that they can be changed and reused independently.

  • The change of one object will lead to the change of one or more other objects, but we don’t know how many objects will change, which can reduce the coupling between objects.

  • An object must notify other objects without knowing who those objects are.

  • You need to create a trigger chain in the system, the behavior of An object will affect B object, and the behavior of B object will affect C object. You can use observer mode to create a chained trigger mechanism

注意事项: 2. Avoid circular references. 3. If executed sequentially, an observer error will cause the system to jam, usually in an asynchronous way.

6.22.2. Realize

The observer mode uses three classes, Subject, Observer, and Client. The Subject object has methods to bind the observer to and unbind the observer from the Client object. We create Subject Class, Observer Abstract classes and extension of abstract classes Observer The entity class of the

ObserverPatternDemo Our demo class uses the Subject And entity class objects to demonstrate the observer pattern.

观察者模式的 UML 图

6.22.3. Step 1

Create the Subject class.

Subject.java

importjava.util.ArrayList;importjava.util.List;publicclassSubject{privateList<Observer>observers=newArrayList<Observer>();privateintstate;publicintgetState(){returnstate;}publicvoidsetState(intstate){this.state=state;notifyAllObservers();}publicvoidattach(Observerobserver){observers.add(observer);}publicvoidnotifyAllObservers(){for(Observerobserver:observers){observer.update();}}}

6.22.4. Step 2

Create the Observer class.

Observer.java

publicabstractclassObserver{protectedSubjectsubject;publicabstractvoidupdate();}

6.22.5. Step 3

Create an entity observer class.

BinaryObserver.java

publicclassBinaryObserverextendsObserver{publicBinaryObserver(Subjectsubject){this.subject=subject;this.subject.attach(this);}@Overridepublicvoidupdate(){System.out.println("Binary
String:"+Integer.toBinaryString(subject.getState()));}}

OctalObserver.java

publicclassOctalObserverextendsObserver{publicOctalObserver(Subjectsubject){this.subject=subject;this.subject.attach(this);}@Overridepublicvoidupdate(){System.out.println("Octal
String:"+Integer.toOctalString(subject.getState()));}}

HexaObserver.java

publicclassHexaObserverextendsObserver{publicHexaObserver(Subjectsubject){this.subject=subject;this.subject.attach(this);}@Overridepublicvoidupdate(){System.out.println("Hex
String:"+Integer.toHexString(subject.getState()).toUpperCase());}}

6.22.6. Step 4

Use Subject And physical observer objects.

ObserverPatternDemo.java

publicclassObserverPatternDemo{publicstaticvoidmain(String[]args){Subjectsubject=newSubject();newHexaObserver(subject);newOctalObserver(subject);newBinaryObserver(subject);System.out.println("First
state change: 15");subject.setState(15);System.out.println("Second state
change: 10");subject.setState(10);}}

6.22.7. Step 5

Execute the program and output the result:

First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.