Observer pattern

2024. 12. 8. 09:57·Frontend/JS Patterns

 

With the observer pattern,

we can subscribe certain objects, the observers, to another object, called the observable.

 

Whenever an event occurs, the observable notifies all its observers!

 

  • observers: an array of observers that will get notified whenever a specific event occurs

An observable object usually contains 3 important parts:

 

  • subscribe(): a method in order to add observers to the observers list
  • unsubscribe(): a method in order to remove observers from the observers list
  • notify(): a method to notify all observers whenever a specific event occurs

 

Code Example

// observable.js

class Observable {
  constructor() {
    this.observers = [];
  }

  subscribe(f) {
    this.observers.push(f);
  }

  unsubscribe(f) {
    this.observers = this.observers.filter(subscriber => subscriber !== f);
  }

  notify(data) {
    // function 들이 Data 를 이용하여 실행된다.
    this.observers.forEach(observer => observer(data)); 
  }
}

export default new Observable();

 

// App.js

import React from "react";
import { Button, Switch, FormControlLabel } from "@material-ui/core";
import { ToastContainer, toast } from "react-toastify";
import observable from "./Observable";

function handleClick() {
  observable.notify("User clicked button!"); // 값은 data
}

function handleToggle() {
  observable.notify("User toggled switch!"); // 값은 data
}

function logger(data) {
  console.log(`${Date.now()} ${data}`);
}

function toastify(data) {
  toast(data, {
    position: toast.POSITION.BOTTOM_RIGHT,
    closeButton: false,
    autoClose: 2000
  });
}

observable.subscribe(logger); // logger 함수를 구독에 추가
observable.subscribe(toastify); // toastify 함수를 구독에 추가

export default function App() {
  return (
    <div className="App">
      <Button variant="contained" onClick={handleClick}>
        Click me!
      </Button>
      <FormControlLabel
        control={<Switch name="" onChange={handleToggle} />}
        label="Toggle me!"
      />
      <ToastContainer />
    </div>
  );
}

Pros

  • Using the observer pattern is a great way to enforce separation of concerns and the single-responsiblity principle.
  • The observer objects aren’t tightly coupled to the observable object, and can be (de)coupled at any time.
  • The observable object is responsible for monitoring the events, while the observers simply handle the received data.

Cons

If an observer becomes too complex, it may cause performance issues when notifying all subscribers.

'Frontend > JS Patterns' 카테고리의 다른 글

Module pattern  (0) 2024.12.08
Mixin pattern  (0) 2024.12.08
Middleware Pattern  (0) 2024.12.08
Mediator Pattern  (0) 2024.12.08
Flyweight Pattern  (0) 2024.12.08
'Frontend/JS Patterns' 카테고리의 다른 글
  • Module pattern
  • Mixin pattern
  • Middleware Pattern
  • Mediator Pattern
JTB
JTB
웹/앱 개발 정보를 공유하고 있습니다.
  • JTB
    JTechBlog
    JTB
  • 전체
    오늘
    어제
    • All About Programming;) N
      • Computer Science
        • Terminology and Concepts
        • Network
        • Operating System
        • Database
        • Data Structure
      • Frontend
        • Javascript Essentials
        • Perfomance Optimization
        • JS Patterns
        • Next.js
        • Flutter
      • Backend
        • Node.js
      • DevOps
        • Docker & Kubernetes
      • Coding Test N
        • LeetCode N
        • Programmers
      • Tech Books & Lectures
        • Javascript_Modern JS Deep d..
        • Network_IT 엔지니어를 위한 네트워크 입문
      • Projects
        • PolyLingo_2025
        • Build Your Body_2024
        • JStargram_2021
        • Covid19 Tracker_2021
        • JPortfolio_2021
      • BootCamp_Codestates
        • TIL
        • TILookCloser
        • Pre Tech Blog
        • IM Tech Blog
        • Daily Issues and DeBugging
        • First Project
        • Final Project
        • Sprint Review
        • Good to Know
        • Socrative Review
        • HTML &amp; CSS
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 글쓰기
    • 관리
  • 공지사항

  • 인기 글

  • 태그

    자바스크립트 딥다이브
    VoiceJournal
    프론트엔드 성능 최적화 가이드
    Network
    database
    Shared resources
    Time complexity and Space complexity
    polylingo
    DOM
    Binary Tree BFS
    How memory manage data
    need a database
    Data Structure
    leetcode
    CPU scheduling algorithm
    TCP/IP
    커리어
    딥다이브
    js pattern
    Threads and Multithreading
    indie hacker
    자바스크립트
    mobile app
    스코프
    모던 자바스크립트 Deep Dive
    Operating System
    testing
    structure of os
    이벤트
    JavaScript
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
JTB
Observer pattern
상단으로

티스토리툴바