在面对这样的项目时,我们首先需要做的是对这个项目进行几个反面的分析:
1.需求分析
这个项目中的角色有两种:普通的用户(也就是借书还书的读者们)和管理员(也就是在后台操作管理这个系统的工作人员)
那么接着针对不同的角色就会进行不同的操作
针对普通用户,我们这个系统支持的操作是:
(1)查找书籍
(2)借阅书籍
(3)归还书籍
针对管理员,我们这个系统支持的操作是:
(1)查找书籍
(2)增加书籍
(3)删除书籍
(4)打印所有的书籍信息
2.概要设计
针对一个具体的项目,我们应该提前思考清楚这个系统项目应该能被分为几个模块,这每个模块都有书名功能作用,然后模块之间又是如何进行交互的。
由于图书馆管理系统这个项目程序过于简单,所有当前我们整个代码只有一个模块
3.详细设计
针对每个具体的模块中的更加详细的细节进行讨论和思考
4.开始编码
先创建类,把核心的类设计好,在类的设计过程中,我们只需要在前面的需求中查找关键词(名词)例如:Book, BookList, NormalUser, Admin(管理员)
注意:
针对前面考虑的一些操作(例如查找删除借阅等),可以通过以下两种方法来实现:
(1)把这些操作作为User(也就是NormalUser和Admin的父类)类方法来实现
(2)可以把这些操作理解为名词,每种操作对应一个类,User类只要持有这些类的实例就可以在本次编码中采用次方法
源码:
1.在book包中
(1)创建Book类
public class Book {
private String name;
private String id;
private String author;
private int price;
private String type;
private boolean isBorrowed;
public Book(String name, String id, String author,
int price, String type, boolean isBorrowed) {
this.name = name;
this.id = id;
this.author = author;
this.price = price;
this.type = type;
this.isBorrowed = isBorrowed;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public boolean isBorrowed() {
return isBorrowed;
}
public void setBorrowed(boolean borrowed) {
isBorrowed = borrowed;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", author='" + author + '\'' +
", price=" + price +
", type='" + type + '\'' +
", isBorrowed=" + isBorrowed +
'}';
}
}
(2)创建BookList类
import package5.B;
public class BookList {
//一共由 100 本书
private Book[] books = new Book[100];
//现在由 size 本书
private int size;
public BookList() {
books[0] = new Book("金瓶梅",
"001","兰陵笑笑生",
100,"古典名著",false);
books[1] = new Book("水浒传",
"002","施耐庵",
100,"古典名著",false);
books[2] = new Book("西游记",
"003","吴承恩",
100,"古典名著",false);
size = 3;
}
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return size;
}
public Book getBook(int index) {
return books[index];
}
public void setBook(int index