search
HomeWeb Front-endJS TutorialLet's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

This article will introduce you to the publish-subscribe and observer patterns, and talk about the differences between the two. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Let's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

Some time ago, I had a whim and wrote promises one by one. Promise happens to be the subscription publishing model. The mobx used for development at work is also an observer model. Although they are all used, but I have never thought about the difference between the two, and the difference analysis on the Internet is confusing. I will combine a summary of my own and the simplest implementation (it is also easy to understand because it is simple) to share and deepen my understanding of the two

subscribe to publish

1. Implementation ideas

  • arr Make a cache center for subscribed events
  • Push the things that need to be done through on the arr cache array Middle
  • When waiting for the event to trigger, emit the execution event in sequence

2. Code implementation

interface eventHub {
  arr: Array<Function>;
  on(fn: Function): void;
  emit(): void;
}
interface Person {
  age: number;
  name: string;
}
let eventHub: eventHub = {
  arr: [] as Array<Function>,
  // 订阅
  on(fn: Function) {
    this.arr.push(fn);
  },
  //   发布
  emit() {
    this.arr.forEach((fn) => fn());
  },
};
let person: Person = {} as Person;
eventHub.on(() => {
//订阅的事件里判断当 person长度为2时 打印person,
  if (Object.keys(person).length == 2) {
    console.log(person);
  }
});
setTimeout(function () {
  person.age = 27;
  //发布的时候去遍历 this.arr 并执行第一次
  eventHub.emit();
}, 10);
setTimeout(function () {
  person.name = "Zoe";
  //发布的时候去遍历 this.arr 并执行第二次
  eventHub.emit();
}, 20);

3.Result

Although it was published twice, in the end the console in on was only executed once due to external conditions

Lets briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

Observer mode

1. Implementation idea

is similar to the observer pattern, but needs to be divided into an observer and the observed

  • The observer and the observed Observers are associated, (internally based on the publish-subscribe model)

2. Code implementation

// 被观察者
class Subject {
  name: string; //实例上定义一个name属性
  state: string;
  observers: any[];
  constructor(name:string) {
    this.name = name;
    this.observers = [];
    this.state = "";
  }
  attach(o) {
    //传入观察者
    this.observers.push(o);
  }
  setState(newState) {
    this.state = newState;
    this.observers.forEach((o) => o.update(this));
  }
}
// 观察者
class Observer {
  name: string;
  constructor(name) {
    this.name = name;
  }
  update(interviewee) {
    console.log(`${interviewee.name} say to: ${this.name} ZOE的${interviewee.state}`);
  }
}
let hr = new Subject("HR");
let observer1 = new Observer("内推者");
let observer2 = new Observer("面试者");
hr.attach(observer1);
hr.attach(observer2);
hr.setState("面试通过了");
// baby.setState("面试没通过");

3. Implementation result

Lets briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

The difference between the two

eventHub publish and subscribe

  • on(subscribe ) and publishing (emit). There is no direct connection between them. They rely on the intermediate arr to connect and subscribe one push to arr. When emitting, arr is executed in sequence

##Observer mode

    There is a relationship between the observer and the observed, (internally based on the publish-subscribe model)
  • Pass the instance of the observer as a parameter into the attach method of the observed and cache it in In the observers array
  • When the observer setState is called, the update method of the observer in the cache array observers is called sequentially
For more programming-related knowledge, please visit:

Programming Video! !

The above is the detailed content of Let's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.