Second, the Library class is the class that contains all the data for the library. Therefore the Library class plays the role of the model. Therefore the Library class needs to keep an arraylist of model listeners that need to be notified every time the library (the model) changes. 1. Add to the Library class an private instance variable, an arraylist of ModelListener. When a library is created, it has an empty arraylist of listeners. 2. Also add to the Library class an addListener method that takes a ModelListener as argument and adds it to the arraylist of listeners. 3. Also add to the Library class a private notifyListeners method that takes nothing as argument and calls the update method of all the listeners of the library. 4. Then change the addUser and moreBook methods so that they call the notifyListeners every time a change is made to the library's data (only the addUser and moreBook methods change the library’s data, so only these two methods need to call the notifyListeners method; the totalBorrowedBooks and getBook methods do not change the library’s data, they only inspect the data, so they do not need to call the notifyListeners method).
时间: 2023-07-03 14:05:00 浏览: 58
Sure, here's an updated version of the Library class with the changes you described:
```
import java.util.ArrayList;
public class Library {
private ArrayList<User> userList;
private ArrayList<Book> bookList;
private ArrayList<ModelListener> listeners;
public Library() {
userList = new ArrayList<User>();
bookList = new ArrayList<Book>();
listeners = new ArrayList<ModelListener>();
}
public void addUser(User user) {
userList.add(user);
notifyListeners();
}
public void moreBook(Book book) {
bookList.add(book);
notifyListeners();
}
public int totalBorrowedBooks() {
int count = 0;
for (User user : userList) {
count += user.getBorrowedBooks().size();
}
return count;
}
public Book getBook(String title) {
for (Book book : bookList) {
if (book.getTitle().equals(title)) {
return book;
}
}
return null;
}
public void addListener(ModelListener listener) {
listeners.add(listener);
}
private void notifyListeners() {
for (ModelListener listener : listeners) {
listener.update();
}
}
}
```
As you can see, we added a `listeners` instance variable to keep track of all the model listeners, an `addListener` method to add new listeners to the list, and a `notifyListeners` method to call the `update` method of all the listeners whenever the library's data changes.
We also modified the `addUser` and `moreBook` methods to call `notifyListeners` after adding a new user or book to the corresponding list.
Note that we didn't change the `totalBorrowedBooks` and `getBook` methods since they only inspect the library's data and don't modify it.