Flyweight Pattern

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

Flyweight 패턴은 비슷한 객체를 대량으로 생성할 때 메모리를 보존하는 데 유용한 방법입니다.

 

class Book {
  constructor(title, author, isbn) {
    this.title = title;
    this.author = author;
    this.isbn = isbn;
  }
}

const books = new Map(); // 중복된 책은 제외됨
const bookList = []; // 중복된 책 포함 - 즉, 복사본이 있음.

const addBook = (title, author, isbn, availability, sales) => {
  const book = {
    ...createBook(title, author, isbn),
    sales,
    availability,
    isbn
  };

  bookList.push(book);
  return book;
};

const createBook = (title, author, isbn) => {
  const existingBook = books.has(isbn); // 존재여부 판단

  if (existingBook) {
    return books.get(isbn); // 존재하면 기존 책 정보를 리턴함.
  }

  const book = new Book(title, author, isbn);
  books.set(isbn, book); // 존재하지 않으면 isbn 번호와 책 정보를 저장.

  return book;
};

addBook("Harry Potter", "JK Rowling", "AB123", false, 100);
addBook("Harry Potter", "JK Rowling", "AB123", true, 50);
addBook("To Kill a Mockingbird", "Harper Lee", "CD345", true, 10);
addBook("To Kill a Mockingbird", "Harper Lee", "CD345", false, 20);
addBook("The Great Gatsby", "F. Scott Fitzgerald", "EF567", false, 20);

console.log("Total amount of copies: ", bookList.length); // 5
console.log("Total amount of books: ", books.size); // 3

 

 

createBook(title, author, isbn) example

 

Map 은 아래와 같이 key 와 value 쌍으로 이루어져 있습니다.

 

books 의 사이즈를 통해 알 수 있듯, books.has(isbn) 를 통해 중복되는 키값을 갖는 경우, 추가하지 않습니다.

 

이처럼 Flyweight 패턴은 사용 가능한 모든 RAM을 잠재적으로 고갈시킬 수 있는 엄청난 수의 객체를 생성할 때 유용하여 소모되는 메모리 양을 최소화할 수 있습니다.

 

다만, JavaScript에서는 프로토타입 상속을 통해 이 문제를 쉽게 해결할 수 있는데,

오늘날 하드웨어는 GB의 RAM을 가지고 있어 플라이웨이트 패턴이 이전보다 덜 중요해졌습니다.

 

 

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

Mixin pattern  (0) 2024.12.08
Middleware Pattern  (0) 2024.12.08
Mediator Pattern  (0) 2024.12.08
Factory Pattern  (0) 2024.12.08
Command Pattern  (0) 2024.11.09
'Frontend/JS Patterns' 카테고리의 다른 글
  • Middleware Pattern
  • Mediator Pattern
  • Factory Pattern
  • Command 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 & CSS
  • 블로그 메뉴

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

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

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
JTB
Flyweight Pattern
상단으로

티스토리툴바