当前位置:网站首页>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 !
边栏推荐
- 2022 recommended high-speed rail industry research report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously
- 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
- 嵌入式RTOS
- Can I cast int to a variable of type byte? What happens if the value is larger than the range of byte type?
- Call the computer calculator and use it to convert several base numbers
- The win11 file resource manager has an explicit Caton, and Microsoft promises to improve the performance in 2022
- 证券开户安全么,有没有什么危险呢
- Embedded RTOS
- What is MES? What does it do?
- D parallel and rotator
猜你喜欢

PCI Verilog IP

Openfpga wishes you a happy Lantern Festival!

Difference between parametric continuity and geometric continuity

Manual (functional) test 1

Two houses with different colors and the farthest distance

HTTP Caching Protocol practice

Will the order of where conditions in MySQL affect the union index? Will where 1 =1 affect the use of the index? Does where 1 =1 affect the use of indexes?

Research Report on recommended specialized, special and new industries in 2022 industry development prospect and market investment analysis (the attachment is a link to the online disk, and the report

2022 recommended trend toy blind box industry research report industry development prospect market analysis white paper (the attachment is a link to the network disk, and the report is continuously up

Output various graphics and text on the console through C #
随机推荐
证券开户安全么,有没有什么危险呢
Analysis report on the investment market of the development planning prospect of the recommended wind power industry research industry in 2022 (the attachment is a link to the network disk, and the re
What are the uses of static?
Pytest (7) -yield and termination function
Spark saving to external data source
There are two ways for golang to develop mobile applications
Agile invincible event
Rearrangement string of leetcode simple question
Difference between parametric continuity and geometric continuity
RTOS embarqués
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
2-nitro-5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin (no2tdmpp) H2) /5,10,15,20-tetra (4-methylphenyl) porphyrin (TMPP) H2) Qiyue porphyrin products
Boost the digital economy and face the future office | the launch of the new version of spreadjsv15.0 is about to begin
ES6 Modularization: export /import
Why can't the article be posted?
Summary of redis basic knowledge points
Is there any difference between a=a+b and a+=b?
Skills of writing test cases efficiently
Is it safe to open a securities account? Is there any danger
Common methods for describing 3D models of objects and their advantages and disadvantages