当前位置:网站首页>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 !
边栏推荐
- Plugin
- Boost the digital economy and face the future office | the launch of the new version of spreadjsv15.0 is about to begin
- [C language series] - initial C language (4)
- [C language series] - branch and loop statements
- Sum of digits under k-ary representation of leetcode simple problem
- Is it safe to open a securities account? Is there any danger
- Pytest (7) -yield and termination function
- Blip: conduct multimodal pre training with cleaner and more diverse data, and the performance exceeds clip! Open source code
- Hyperledger Fabric 2. X custom smart contract
- ASP. Net core 6 framework unveiling example demonstration [03]:dapr initial experience
猜你喜欢

Creation of Arduino uno development environment

PCI Verilog IP

It turns out that the joys and sorrows of programmers are not interlinked

How to use thread stack location

Meta metauniverse female safety problems occur frequently. How to solve the relevant problems in the metauniverse?

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

Programming specification and variables of shell script
![[high concurrency] deeply analyze the callable interface](/img/fb/89ebd5592f1383c8015a47cec78a59.jpg)
[high concurrency] deeply analyze the callable interface

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

Analysis report on the investment market of the development planning prospect of the recommended rare earth industry research industry in 2022 (the attachment is a link to the online disk, and the rep
随机推荐
Meso tetra (4-N, N, n-trimethylaminophenyl) porphyrin (ttmapp) /meso tetra - [4- (BOC threonine) aminophenyl] porphyrin (TAPP thr BOC) supplied by Qiyue
What is MES? What does it do?
There are two ways for golang to develop mobile applications
After nine years of testing, the salary for interviewing Huawei is 10000. Huawei employees: the company doesn't have such a low salary position
Open source demo| you draw and I guess -- make your life more interesting
Segment in Lucene
How to hand over complex legacy systems?
QT precautions and RCC download address
Week 12 - task 2- shoulder to shoulder cadres
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
Signal slot mechanism
Sourcetree remote red exclamation point
Hyperledger Fabric 2. X custom smart contract
DANGER! V** caught climbing over the wall!
Plugin
The translation of those exquisite lines in the eighth season of the big bang
64 commonly used terms for data analysis, really all!
How to insert pseudo code into word documents simply and quickly?
Clickhouse data type
Can I cast int to a variable of type byte? What happens if the value is larger than the range of byte type?