Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The Observer pattern of messing with Java Design pattern

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Observer mode

Define an one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.

Literally, one-to-many dependencies between objects are defined, and all dependencies are automatically notified and updated when the state of an object changes. Such as publish / subscribe mode, event notification mode, data source / listening mode, etc. are all the same in nature.

Observer mode UMLUML classes and sequence diagrams

Class diagram: the Subject class does not directly update the state of dependent objects. Instead, Subject refers to the observer interface (update ()) used to update the state, which makes Subject independent of how the dependent object updates its state. The Observer1 and Observer2 classes implement the Observer interface by synchronizing the state with the state of the Subject.

Timing diagram: the Observer1 and Observer2 objects call attach (this) on Subject1 to register themselves. If the state of the Subject1 changes, the Subject1 itself calls notify (). Notify () calls update () on registered Observer1 and Observer2 objects, which requests changed data (getState ()) from Subject1 to update (synchronize) its state.

Cdn.xitu.io/2019/4/8/169fa85625382e27?w=600&h=240&f=jpeg&s=26680 ">

UML class diagram

Observer mode role

Subject (goal): a goal, also known as a topic, refers to the object being observed. A set of observers is defined in the target, which can be observed by any number of observers, it provides a series of methods to add and delete observer objects, and it defines the notification method notify (). The target class can be an interface, an abstract class, or a concrete class.

ConcreteSubject (specific goal): a specific goal is a subclass of the target class, which usually contains data that changes frequently and notifies its observers when its state changes; it also implements abstract business logic methods, if any, defined in the target class. If you do not need to extend the target class, the specific target class can be omitted.

Observer (observer): the observer will react to the change of the observation object. The observer is generally defined as an interface, which declares the method update () to update the data, so it is also called the abstract observer.

ConcreteObserver (concrete observer): maintains a reference to a specific target object in the concrete observer, which stores the relevant states of the specific observer, which need to be consistent with the state of the specific target; it implements the update () method defined in the abstract observer Observer.

The Observer pattern describes how to establish dependencies between objects and how to construct a system that meets this requirement. The observer mode includes two types of objects: the observation target and the observer. A target can have any number of dependent observers. Once the state of the observation target changes, all observers will be notified. In response to this notification, each observer monitors the status of the observation target to synchronize its status with the target state, an interaction also known as publish-subscribe (Publish-Subscribe). The observation target is the publisher of the notification, it does not need to know who its observer is when it sends the notification, and any number of observers can subscribe to it and receive notifications.

Analysis of source code of practical information

Source code address

Blog subscription function, maintaining subscription relationships in abstract topics, while introducing ordinary and vip watchers.

/ / Abstract topic @ Datapublic abstract class Subject {/ / topic subscribers private List observerList = Lists.newArrayList (); / / subscribe to public void register (Observer observer) {observerList.add (observer);} / unsubscribe to public void remove (Observer observer) {observerList.remove (observer);} / publish something public abstract void publish (String msg) } / / Abstract Observer @ Slf4j@Data@AllArgsConstructorpublic abstract class Observer {/ / Observer name private String name; / / update status by topic dispatching public void update (Object subject, Object args) {log.info ("{} get change notification: {}", name, args) }} / / blog topic @ Slf4jpublic class Blog extends Subject {@ Override public void publish (String msg) {log.info ("publish msg: {}", msg); / / notify subscribers getObserverList () .forEach (observer-> observer.update (this, msg));}} / / ordinary user watchers @ Slf4jpublic class NormalObserver extends Observer {public NormalObserver (String name) {super (name) } @ Override public void update (Object subject, Object args) {super.update (subject, args); log.info ("{} get change notification: ordinary users can not cache", getName ());}} / / vip user Observer @ Slf4jpublic class VipObserver extends Observer {public VipObserver (String name) {super (name) } @ Override public void update (Object subject, Object args) {super.update (subject, args); log.info ("{} get change notification: vip can be cached", getName ());} @ Slf4jpublic class Application {public static void main (String [] args) {Blog blog = new Blog (); VipObserver wang = new VipObserver ("Lao Wang 99"); VipObserver lee = new VipObserver ("Lao Li") NormalObserver four = new NormalObserver ("Xiao Si"); NormalObserver twoEgg = new NormalObserver ("two eggs"); log.info ("- begin-"); / / users subscribe to blogs, ordinary and vip users new Thread (()-> {blog.register (wang)) Sleep (2); blog.register (lee); sleep (2); blog.register (four);}) .start () / / the blog thread publishes articles every 2 seconds for a total of 4 times new Thread (()-> {IntStream.rangeClosed (1,4) .forEach (I-> {blog.publish (String.format (% s); sleep (2);}). Start () / some users quit to subscribe to the blog, while others join the subscription new Thread (()-> {sleep (3); blog.remove (lee); sleep (2); blog.register (twoEgg);}) .start () } private static void sleep (int seconds) {try {TimeUnit.SECONDS.sleep (seconds);} catch (InterruptedException e) {log.error ("error:", e);}

Obverser and Observable built into jdk

@ Slf4jpublic class ObserverApplication {public static void main (String [] args) {log.info ("Enter Text:"); EventSource eventSource = new EventSource (); eventSource.addObserver ((obj, arg)-> {log.info ("Received response: {}", arg);}) EventSource.addObserver ((obj, arg)-> {log.info ("Received response2: {}, {}", arg, obj); new Thread (eventSource). Start ();}} class EventSource extends Observable implements Runnable {public void run () {while (true) {String response = new Scanner (System.in). Next () Use in setChanged (); notifyObservers (response);} Java

It gives an object the flexibility to send messages to interested objects.

Java.util.EventListener

Javax.servlet.http.HttpSessionBindingListener

Javax.servlet.http.HttpSessionAttributeListener

Javax.faces.event.PhaseListener

Listener can see from the name what it means to monitor.

Obverser and Observable built into JDK

Observer mode built into jdk. That is, java.util.Observer (interface) and java.util.Observable (class).

Let's talk about this briefly. Observer interface (java.util.Observer), topic (java.util.Observable). Implement the observer interface and inheritance topics. Register the observer by abstracting the topic's addObserver (), and deleteObserver () removes the observer.

First, the state change is notified by calling the setChange () of the topic class, and then the notifyObservers method (parameters can be passed or not) is called to notify the observer. Finally, because the topic takes the initiative to call the observer's update () method during notifyObservers, the change method has two parameters, the first is the topic object, and the second is the variable parameter.

Summary

The Observer pattern is a very frequently used design pattern, and there is an implementation in JDK. Observer pattern is almost ubiquitous in mobile applications, Web applications or desktop applications. It provides a complete solution for realizing the interaction between objects. Observer mode can be used in all scenarios involving one-to-one or one-to-many object interaction. The Observer pattern is widely used in the implementation of GUI event handling in various programming languages. It is also used in event-based XML parsing techniques (such as SAX2) and Web event handling.

Advantages of the observer model

The main results are as follows: (1) the observer pattern can realize the separation of presentation layer and data logic layer, defines a stable message update delivery mechanism, and abstracts the update interface, so that a variety of different presentation layers can act as specific observers.

(2) the observer model establishes an abstract coupling between the observation target and the observer. The observation target only needs to maintain a collection of abstract observers and does not need to know its specific observers. Because the observation target and the observer are not closely coupled, they can belong to different levels of abstraction.

(3) the observer mode supports broadcast communication, and the observation target sends notifications to all registered observer objects, which simplifies the difficulty of one-to-many system design.

(4) the observer mode meets the requirements of the "open and closed principle", adding new specific observers does not need to modify the original system code, and it is convenient to add new observation targets when there is no correlation between the specific observer and the observation target.

The shortcomings of the observer model

(1) if a target 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 target has changed, but only know that the observed target has changed.

Matters needing attention

1. There are already support classes for the Observer pattern in JAVA. 2. Avoid circular references. 3. If executed sequentially, an observer error will cause the system to jam, usually in an asynchronous way.

Referenc

Observer pattern

Observer mode | Rookie tutorial

Count the design patterns in JDK

Design pattern Summary (Java)-Observer pattern

Welcome to follow us.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report