Frontend/JS Patterns

Flyweight Pattern

JTB 2024. 12. 8. 09:30

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을 가지고 있어 플라이웨이트 패턴이 이전보다 덜 중요해졌습니다.