Post

Structural_Flyweight

βœ… Flyweight

  • πŸ‘πŸ» memory optimization, efficiency
  • minimize memory usage by sharing common object data
  • if object is same, do not duplicate ❌
  • λ˜‘κ°™μ€ object이면 또 λ§Œλ“€μ§€ 말고(λ©”λͺ¨λ¦¬ λ‚­λΉ„), κ³΅μœ ν•˜μž

  • What is a common object?
  • Object with all same fields

  • πŸ› οΈ Use when you have to use identical objects here and there
  • πŸ†š singleton: λͺ©μ  - guarantee exactly only one instance of a class in the whole application
  • flyweight: λͺ©μ  - share many reusable objects, to reduce memory usage

βœ… Structure and Diagram

Screenshot-2026-03-06-at-19-27-14.png

  • πŸ‘ŽπŸ» before
1
2
1,000,000 objects
each containing identical data
  • πŸ‘πŸ» after
1
1 shared object + lightweight references

πŸ‘€

1. Flyweight class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Flyweight class
class Book {

    private final String title; // intrinsic state (shared)
    // title will not be changed

    public Book(String title) {
        this.title = title;
    }

    public void read() {
        System.out.println("Reading the book titled: " + title);
    }
}

2. Flyweight Factory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// FlyweightFactory class
class Bookshelf {
    //need map to check if same book exists by title
    private static final Map<String, Book> bookshelf = new HashMap<>();

    public static Book getBook(String title) {
        Book book = bookshelf.get(title);

        //check if book with same title exists
        if (book == null) { //if not exists
            book = new Book(title);  //create new book
            bookshelf.put(title, book);
            System.out.println(
                "Adding a new book to the bookshelf: " + title);
        } else {
            System.out.println( //if exsits, use the existring book
                "Reusing existing book from the bookshelf: " + title);
        }
        return book;
    }
}

Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Client code
public class Main {
    public static void main(String[] args) {
        Book book1 = Bookshelf.getBook("Effective Java");
        book1.read();

        Book book2 = Bookshelf.getBook("Effective Java"); //same book
        book2.read();

        Book book3 = Bookshelf.getBook("Clean Code"); //different book
        book3.read();

        // Check if book1 and book2 are the same object
        // book 2 was not created, as the book with same title exists
        System.out.println(
            book1 == book2 ? "Same book for 'Effective Java'."
            : "Different books for 'Effective Java'."
        );
    }
}

πŸ› οΈ

  • when you have to use the same instance several times
  • in different places
This post is licensed under CC BY 4.0 by the author.