forked from code-differently/code-differently-24-q1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Library.java
101 lines (91 loc) · 2.56 KB
/
Library.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.codedifferently.lesson9.LibraryManagementSystem;
import java.util.ArrayList;
import java.util.List;
/** Represents a library that manages a collection of books and patrons. */
public class Library {
private List<Book> books;
private List<Patron> patrons;
/** Constructs a new Library instance with empty collections of books and patrons. */
public Library() {
this.books = new ArrayList<>();
this.patrons = new ArrayList<>();
}
/**
* Adds a book to the library's collection.
*
* @param book The book to be added.
*/
public void addBook(Book book) {
books.add(book);
}
/**
* Removes a book from the library's collection.
*
* @param book The book to be removed.
*/
public void removeBook(Book book) {
books.remove(book);
}
/**
* Registers a new patron with the library.
*
* @param patron The patron to be registered.
*/
public void registerPatron(Patron patron) {
patrons.add(patron);
}
/**
* Checks out a book to a patron.
*
* @param book The book to be checked out.
* @param patron The patron who is checking out the book.
*/
public void checkOutBook(Book book, Patron patron) {
if (!books.contains(book)) {
throw new IllegalArgumentException("Book not found in the library");
}
if (!patrons.contains(patron)) {
throw new IllegalArgumentException("Patron not registered in the library");
}
if (book.isCheckedOut()) {
throw new IllegalStateException("Book is already checked out");
}
book.setCheckedOut(true);
patron.addCheckedOutBook(book);
}
/**
* Returns a book that was checked out by a patron.
*
* @param book The book to be returned.
* @param patron The patron who is returning the book.
*/
public void returnBook(Book book, Patron patron) {
if (!books.contains(book)) {
throw new IllegalArgumentException("Book not found in the library");
}
if (!patrons.contains(patron)) {
throw new IllegalArgumentException("Patron not registered in the library");
}
if (!book.isCheckedOut()) {
throw new IllegalStateException("Book is not checked out");
}
book.setCheckedOut(false);
patron.removeCheckedOutBook(book);
}
/**
* Gets the list of books in the library.
*
* @return The list of books in the library.
*/
public List<Book> getBooks() {
return books;
}
/**
* Gets the list of patrons registered in the library.
*
* @return The list of patrons registered in the library.
*/
public List<Patron> getPatrons() {
return patrons;
}
}