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

How to understand the Observer pattern of Java Design pattern

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge of "how to understand the Observer pattern of Java Design pattern". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. what is the Observer Model

In many designs, multiple objects are often interested in data changes in a particular object, and these objects want to track data changes in that particular object, that is, when there is an one-to-many relationship between objects, observer mode can be used in such cases. When an object is modified, its dependent objects are automatically notified.

The Observer pattern is a mature pattern in which multiple objects want to know how the data changes in one object. In the observer pattern, there is an object called "subject" and several objects called "observer". There is an one-to-many dependency between "subject" and "observer". All observers are notified when the state of the subject changes.

The main solution: the problem of notifying other objects of a change in the state of one object, and taking into account easy to use and low coupling to ensure a high degree of cooperation.

Second, the structure of the observer model

The structure of the observer pattern consists of four roles:

(1) topic (Subject): a topic is an interface that specifies the methods that a specific topic needs to implement, such as adding and deleting observers, and notifying observers to update data.

(2) Observer: an observer is an interface that specifies the method that a specific observer uses to update data.

(3) specific theme (ConcreteSubject): a specific theme is an instance of an implementation theme interface class that contains data that can change frequently. Specific topics need to use a collection, such as ArrayList, to hold references to the observer so that they can be notified when the data changes.

(4) concrete observer (ConcreteObserver): a concrete observer is an instance that implements the observer interface class. The specific observer contains topic interface variables that can store specific topic references, so that the specific observer can let the specific topic add its own references to the collection of specific topics, making itself its observer, or let the specific topic remove itself from the collection of specific topics, so that it is no longer its observer.

Third, the use scenario of the observer mode

(1) other objects need to be notified when the data of one object is updated, but this object does not want to be tightly coupled with the notified objects.

(2) when the data of an object is updated, the object needs to let other objects update their own data, but the object does not know how many objects need to update the data.

Observer mode is very common in practical projects. For example, if you withdraw money from an ATM machine and enter the wrong password many times, the card will be swallowed by ATM. What events will be triggered when card swallowing occurs? The first camera takes snapshots continuously, second, notify the monitoring system, and the card swallowing occurs; third, initialize the ATM screen and return to the original state. You can't swallow a card just because you can't use the whole ATM. Generally, the first two actions are done through observer mode. The observer can broadcast the message, and a message can trigger multiple events, which is a very important function of the observer pattern.

There are also two key issues to be solved in using the observer mode: the problem of the broadcast chain.

If you have ever done a trigger in a database, you should know that there is a problem with the trigger chain. For example, table A has a trigger that updates a piece of data from table B after a field is updated, while table B also has a trigger. To update table C, table C also has a trigger. Oh, it's over, this database is basically destroyed! Our observer model is the same problem. An observer can have a dual identity, even if the observer is also the observed, which is no problem, but once the chain is established, the logic is more complex and the maintainability is very poor. according to empirical advice, at most one object in an observer mode is both the observer and the observed, that is, the message is forwarded at most once (delivered twice). It's easier to control.

Deal with problems asynchronously.

When the observed person moves, the observer has to respond. What if there are more observers and the processing time is longer? Then use asynchrony. Asynchronous processing should consider thread safety and queue issues. If you have time to look at Message Queue, you will have a deeper understanding.

Fourth, the advantages and disadvantages of the observer model

Advantages:

1. The relationship between the specific subject and the specific observer is loosely coupled. Because the topic interface depends only on the observer interface, the specific topic only knows that its observer is an instance of a class that implements the observer interface, but does not need to know which class it is. Similarly, because the observer relies only on the topic interface, the specific observer only knows that the topic it depends on is an instance of a class that implements the topic interface, but does not need to know which class.

2. The observer model satisfies the "open-closed principle". The topic interface depends only on the observer interface, so that the class that creates the specific theme depends only on the observer interface, so if you add a new class that implements the observer interface, you don't have to modify the code of the class that creates the specific theme. Similarly, the class that creates the concrete observer depends only on the topic interface, and if you add a new class that implements the theme interface, you don't have to modify the code that creates the concrete observer class.

Disadvantages:

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.

Fifth, the realization of the observer model

The Observer class-Abstract Observer, defines an interface for all concrete observers and updates itself when notified by the topic.

This interface is called an update interface, and abstract observers are generally implemented as an abstract class or an interface. Update interfaces usually include a Update method, which is called an update method.

Abstract class Observer {public abstract void Update ();}

Subject class-topic or abstract notifier, usually implemented with an abstract class or an interface.

It saves all references to the observer object into a collection, and each topic can have any number of observers. Abstract topics provide an interface to add and remove observers.

Abstract class Subject {private List observers = new List (); / / add observer public void Attach (Observer observer) {observers.Add (observer);} / remove observer public void Detach (Observer observer) {observers.Remove (observer);} / / notify public void Notify () {foreach (var item in observers) {item.Update () }}}

ConcreteSubject class-specific topic or specific notifier, store the relevant status in the specific observer object; when the internal state of the specific topic changes, send a notification to all registered observers.

Specific topic roles are usually implemented with a concrete class.

Class ConcreteSubject: Subject {private string subjectState; / / specific observer status public string SubjectState {get {return subjectState;} set {subjectState = value;}

The ConcreteObserver class-concrete observer, implements the update interface required by the abstract observer role in order to reconcile its own state with that of the topic.

A specific observer role can save a reference to a specific subject object. The specific observer role is usually implemented with a concrete class.

Class ConcreteObserver: Observer {private string name; private string observerState; private ConcreteSubject subject; public ConcreteObserver (ConcreteSubject subject, string name) {this.subject = subject; this.name = name;} public override void Update () {observerState = subject.SubjectState; Console.WriteLine ("New status of Observer {0} is {1}", name, observerState);} public ConcreteSubject Subject {get {return subject } set {subject = value;}

Client code

Static void Main (string [] args) {ConcreteSubject cs = new ConcreteSubject (); cs.Attach (new ConcreteObserver (cs, "X")); cs.Attach (new ConcreteObserver (cs, "Y")); cs.Attach (new ConcreteObserver (cs, "Z")); cs.SubjectState = "ABC"; cs.Notify (); Console.Read ();}

Result

The new state of Observer X is ABC.

The new state of Observer Y is ABC

The new state of Observer Z is ABC

VI. The combination of observer mode and delegation

Although the above code has used the dependency inversion principle, the "abstract notifier" still relies on the "abstract observer", that is, if there is no interface such as the abstract observer, the notification function cannot be sent.

In addition, for each specific observer, it is not necessarily a method call to Update.

Purpose: the notifier and the observer do not know each other at all, and it is up to the client to decide who to notify

/ / Notifier interface interface Subject {void Notify (); string SubjectState {get; set;}}

Specific observer class

/ / class StockObserver {private string name; private Subject sub; public StockObserver (string name, Subject sub) {this.sub = sub; this.name = name;} / / close stock public void CloseStock () {Console.WriteLine ("{0} {1} close stock and continue to work", sub.SubjectState, sub);}} / / look at NBA colleague class NBAObserver {private string name Private Subject sub; public NBAObserver (string name, Subject sub) {this.sub = sub; this.name = name;} / / close NBA public void CloseNBA () {Console.WriteLine ("{0} {1} close NBA, continue to work", sub.SubjectState, sub);}}

Declare a delegate, no parameters, no return value

/ / declare a delegate with no parameters and no return value delegate void EventHandler ()

Subject or abstract notifier

/ / Boss class class Boss: Subject {private string action; / / declare delegate event Update public event EventHandler Update; public string SubjectState {get {return action;} set {action = value;}} public void Notify () {/ / call Update Update () when accessing notification }} / / Secretary class class Secretary: Subject {/ / similar to boss class, omit.}

Client code

Static void Main (string [] args) {/ / Boss Zhang Boss Zhang = new Boss (); StockObserver tongshi1 = new StockObserver ("Zhang San", Zhang); NBAObserver tongshi2 = new NBAObserver ("Li Si", Zhang); Zhang.Update + = new EventHandler (tongshi1.CloseStock); Zhang.Update + = new EventHandler (tongshi2.CloseNBA); Zhang.SubjectState = "Boss Zhang is here!" ; Zhang.Notify (); Console.Read ();}

Result

Boss Zhang is here! Zhang San closes the stock and continues to work. The boss Zhang is here! Li Si closes NBA and continues to work on "how to understand the Observer pattern of Java Design patterns". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report