当前位置:网站首页>Observer mode vs publish subscribe mode
Observer mode vs publish subscribe mode
2022-06-29 06:04:00 【Dotnet cross platform】

Preface
The name of observer mode , You must have heard about it . From our real life , Subscribe to wechat official account 、 Hospital registration and so on all belong to its practical application . In the world of programs , It is a design pattern for decoupling code , If you want to master and understand this design pattern , Today, come with me to explore its mysteries !

Observer mode
When we talked about the event mechanism earlier , We've actually mentioned the observer model . The observer pattern actually implements a communication mechanism , That is, the mechanism by which the observation target notifies the observer . Under the premise of low coupling design , The observer does not need to directly call the internal methods or properties of the observation target to get the notification , But use “ subscribe ” To get notifications , The general flow chart is as follows :

Combined with actual development examples , stay C# We only need to define the corresponding delegate and event , The use of observer mode , For detailed usage, please refer to my previous articles : We can talk C# Delegate and event in , No more details here .
But in other languages , for example Java, It does not provide a mechanism like delegation or event for callback , Therefore, the implementation will be slightly cumbersome , The related class diagram is as follows :

In this way of implementation , We need to look at the target , That is to say, the theme is abstracted , That is... In the picture Subject, Used to provide a collection of saved observers ( In the picture ArrayList), And the method of adding or deleting observers . But in the specific subject ( In the picture ConcreteSubject) in , Contains the state attribute , And the method of state change , When you change yourself , Would call notifyObserver Method to notify .
In the observer's implementation , There are also abstract observers (Observer) And specific observers (ConcreteObserver) Two characters . The former generally defines an interface , Used when a change notification is received , Update yourself . The latter will achieve concrete update Method , similar C# Callback method triggered after we subscribe to events in .
This is how we implement the observer pattern in both languages , As software engineering emphasizes “ There is no silver bullet ” That's what I'm saying , The observer model solves many problems , But there are also some disadvantages , The main contents are as follows :
1、 When there are many observers , Notification by notification can be time consuming . As we implemented above , There is one. ArrayList To save all observers , If this ArrayList The elements in are large enough , Then the execution efficiency of the program at the time of notification is bound to be very low .
2、 If there is a circular dependency between the observation target and the observer , Observer mode triggers a loop call from both sides , Causing the system to crash .
3、 There is no mechanism to inform the observer of how the objective changes , The observer simply knows that the object of observation has changed . Of course, this is not absolute , When implementing a program, we can pass parameters or objects to “ inform ” The observer , Observe what changes have taken place in the target .
When we talk about observer mode , Repeatedly mentioned “ The theme ” and “ subscribe ” The concept of . Conceptually speaking , It seems that observer mode , It's about publishing - A subscription model , So is there any difference between the two ? Let's move on to the next chapter to explore .

Publish subscribe mode
in fact , Publish subscribe mode , It is different from the observer mode . Back to our initial example , Subscription to WeChat official account , Seems to be paying direct attention to the official account , In essence , In the two behaviors of attention and push , It's all through “ WeChat public platform ” This is implemented by a third party . See here , Smart people should be able to understand the differences between publish and subscribe modes , you 're right , The publish subscribe mode is based on the observer mode , Joined the “ Event center ” The concept of :

Through the event center , Publishers and subscribers are further decoupled , Publishers don't need to care about subscribers' subscriptions , Instead, you can directly publish the topic to the event center . And subscribers don't have to care about the publisher's own situation , I don't even know who the publisher is , Just receive the notification from the event center .
Publish subscribe mode is widely used in various message oriented middleware , As is common RabbitMQ,kafka etc. , The publisher publishes the topic , Consumers subscribe to the corresponding topics to consume the published messages , I believe you are not unfamiliar with these concepts .

Summary
thus , The topic we are going to explore today comes to an end for the time being . The observer pattern is so similar to the publish subscribe pattern , But it's different , After we have clarified our respective concepts and implementation methods , It will be found that these two modes are ubiquitous in our daily applications .
Design pattern itself is the precipitation and summary of some best practices and methodologies made by some excellent predecessors in the development process , So when you mention these contents , Don't assume that these things just stay in the conceptual stage , Unable to practice . But need to combine with their actual work , Think carefully about how design patterns should be applied , How to choose the right design pattern , Solve your own problems . Of course , There is never an optimal solution , Abusing design patterns will only greatly reduce the readability of the program , Make it difficult for subsequent maintenance . Active learning and flexible application , Here I wish you all can study with me , Common progress and growth , See you next time !
边栏推荐
- Rich material libraries make modeling easy and efficient for developers
- Week 10 - task 3- from point to circle to cylinder
- Stack -- 739 Daily temperature
- 5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin ((tdmpp) H2) /2-nitro-5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin copper (no2tdmpp) Cu) supplied by Qiyue
- Problems with MySQL database query
- How to use regex in file find
- 2022 recommended property management industry research report industry development prospect market investment analysis (the attachment is the link to the online disk, and the report is continuously up
- Conditional test, if and case conditional test statements of shell script
- CCTV revealed that xumengtao won the black Technology: there was a virtual coach???
- Modularization and modular specification commonjs
猜你喜欢

Difference between parametric continuity and geometric continuity

There are two ways for golang to develop mobile applications

What has urbanization brought to our mental health and behavior?

2022 recommended quantum industry research industry development planning prospect investment market analysis report (the attachment is a link to the online disk, and the report is continuously updated

HTTP Caching Protocol practice

JIRA basic usage sharing

Agile invincible event

Pytest (7) -yield and termination function

Rearrangement string of leetcode simple question

Why can't the article be posted?
随机推荐
Multiline regular expression search in Visual Studio code - multiline regular expression search in Visual Studio code
Analysis report on the investment market of the development planning prospect of the recommended NFT industry research industry in 2022 (the attachment is a link to the online disk, and the report is
Installing modules in pycharm
Difference between static and final
VLAN experiment
Difference between parametric continuity and geometric continuity
Internet enterprises need CRM software to help
Est - ce que l'ouverture d'un compte de titres est sécurisée? Y a - t - il un danger?
Rich material libraries make modeling easy and efficient for developers
Is it safe to open a securities account? Is there any danger
Leetcode notes on question brushing (XIV) -- related topics of binary tree attributes in binary tree chapter
Mongodb basic knowledge summary
The first in China! CICA technology database antdb appears at the performance test tool conference of China Academy of communications technology
5,10-di (4-aminophenyl) - 15,20-diphenylporphyrin (cis-dadph2) /5,15-di (4-aminophenyl) - 10,20-diphenylporphyrin (trans-dadph2) / (tri-apph2) supplied by Qiyue
What are the uses of final?
CodeIgniter active record not equal - CodeIgniter active record not equal
Regular expressions for shell script values
Analysis report on the investment market situation of the development planning prospect of the recommended chip industry research industry in 2022 (the attachment is a link to the network disk, and th
2022-02 Microsoft vulnerability notification
Signal slot mechanism