---
# System prepended metadata

title: '**OOD筆記(Library Management System - 圖書管理系統)**'
tags: [OOD]

---

# **OOD筆記(Library Management System - 圖書管理系統)**


日期 : 2024/10/12



### **設計**

這個系統需要支持以下需求：

書籍管理：新增、刪除、查找書籍。
借閱和歸還書籍：會員可以借書和歸還書。
會員管理：系統能管理會員的資料和借閱記錄。
限制：每位會員一次只能借一定數量的書籍，例如最多 5 本。
書籍的狀態：書籍可以是「已借出」或「可借閱」


### **實作**

```python
from enum import Enum
from typing import List, Dict

class BookStatus(Enum):
    AVAILABLE = 1
    BORROWED = 2
```

```python
class Book:
    def __init__(self, book_id: str, title: str, author: str):
        self.book_id = book_id
        self.title = title
        self.author = author
        self.status = BookStatus.AVAILABLE

    def is_available(self) -> bool:
        return self.status == BookStatus.AVAILABLE
```

```python
class Member:
    def __init__(self, member_id: str, name: str):
        self.member_id = member_id
        self.name = name
        self.borrowed_books: List[Book] = []

    def borrow_book(self, book: Book) -> bool:
        if len(self.borrowed_books) >= 5:
            print(f"{self.name} has already borrowed the maximum number of books.")
            return False

        if book.is_available():
            book.status = BookStatus.BORROWED
            self.borrowed_books.append(book)
            return True
        return False

    def return_book(self, book: Book) -> bool:
        if book in self.borrowed_books:
            book.status = BookStatus.AVAILABLE
            self.borrowed_books.remove(book)
            return True
        return False
```

```python
class Library:
    def __init__(self):
        self.books: Dict[str, Book] = {}
        self.members: Dict[str, Member] = {}

    def add_book(self, book: Book):
        self.books[book.book_id] = book

    def remove_book(self, book_id: str):
        if book_id in self.books:
            del self.books[book_id]

    def find_book(self, title: str) -> List[Book]:
        book_list = []
        for book in self.books.values():
            if book.title.lower() == title.lower():
                book_list.append(book)
        return book_list

    def add_member(self, member: Member):
        self.members[member.member_id] = member

    def borrow_book(self, book_id: str, member_id: str) -> bool:
        if book_id in self.books and member_id in self.members:
            book = self.books[book_id]
            member = self.members[member_id]
            return member.borrow_book(book)
        return False

    def return_book(self, book_id: str, member_id: str) -> bool:
        if book_id in self.books and member_id in self.members:
            book = self.books[book_id]
            member = self.members[member_id]
            return member.return_book(book)
        return False
```

---

### **測試**


```python
if __name__ == "__main__":
    library = Library()

    # 新增書籍
    book1 = Book("1", "Harry Potter", "J.K. Rowling")
    book2 = Book("2", "The Hobbit", "J.R.R. Tolkien")
    library.add_book(book1)
    library.add_book(book2)

    # 新增會員
    member = Member("1001", "Alice")
    library.add_member(member)

    # 借閱書籍
    if library.borrow_book("1", "1001"):
        print(f"{member.name} borrowed {book1.title}")

    # 嘗試借同一本書
    if not library.borrow_book("1", "1001"):
        print(f"{book1.title} is already borrowed.")

    # 歸還書籍
    if library.return_book("1", "1001"):
        print(f"{member.name} returned {book1.title}")
```

```
Alice borrowed Harry Potter
Harry Potter is already borrowed.
Alice returned Harry Potter
```

---

### **Data Flows**

```
新增書籍和會員：
- 書籍和會員的資料通過 Library.add_book 和 Library.add_member 進入系統。

借閱流程：
- 當會員借書時，系統會檢查書籍是否可借（Book.is_available）
- 若可借，系統更新書籍狀態為 BORROWED，並將該書加入會員的借閱列表

歸還流程：
- 歸還時，系統檢查該會員是否已借過此書。
- 若已借，書籍狀態更新為 AVAILABLE，並從會員借閱列表中移除。
```




---

### **UML 類圖**

```
+------------------------+
|       Library          |
+------------------------+
| - books: List[Book]     |
| - members: List[Member] |
+------------------------+
| + add_book(book: Book): void     |
| + remove_book(book_id: str): void|
| + find_book(title: str): List[Book] |
| + borrow_book(book_id: str, member_id: str): bool |
| + return_book(book_id: str, member_id: str): bool |
+------------------------+

+------------------------+
|        Book            |
+------------------------+
| - book_id: str         |
| - title: str           |
| - author: str          |
| - status: BookStatus   |
+------------------------+
| + is_available(): bool |
+------------------------+

+------------------------+
|       Member           |
+------------------------+
| - member_id: str       |
| - name: str            |
| - borrowed_books: List[Book] |
+------------------------+
| + borrow_book(book: Book): bool |
| + return_book(book: Book): bool |
+------------------------+

+------------------------+
|      BookStatus        |
+------------------------+
| AVAILABLE              |
| BORROWED               |
+------------------------+

```



---


### **細節**




**講解連結**

Provided by. 
