目录
运用学习过的类和对象、封装、继承和多态、抽象类和接口来实现一个简单的图书管理系统。
1、整体框架的搭建
大致分为四个部分
第一个部分是book包——用于存储书籍的信息
第二个部分是operation包——用于实现图书管理的基本操作,例如借阅,归还,显示,删除,新增……
第三个部分是user包——用于区分用户身份,身份不同可操作的功能也不同,例如管理员、普通用户
第四个部分是Main类——用于填写信息从而调取用户界面
2、book包
用于存储书籍的信息
2.1 Book类
每本图书都有它的姓名,作者,价格,种类,以及是否借出的状态,创建这些成员属性,因为这里要体现封装,所以变量一律用private修饰
public class Book {
private String name;
private String author;
private int price;
private String type;//书的类型
private boolean isBorrowed;//默认是false
}
创建Book对象的构造方法,同时提供这些变量的get和set方法,生成toString()方法
public Book(String name, String author, int price, String type) {
this.name = name;
this.author = author;
this.price = price;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isBorrowed() {
return isBorrowed;
}
public void setBorrowed(boolean borrowed) {
isBorrowed = borrowed;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
", type='" + type + '\'' +
(isBorrowed == true ? " 已借出 ":" 未借出 ") +
'}';
}
2.2 BookList类
BookList类比作书架,我们首先定义一个Book类型的数组,用来存放书籍,以及用来描述当前书籍个数的usedSize变量 ,当然Book类型数组的大小为10,即存放的书籍不超过10本
public class BookList {
public Book[] bookList = new Book[10];
private int usedSize;//当前书架上 有几本书
public BookList() {
this.bookList[0] = new Book("三国演义","罗贯中",18,"小说");
this.bookList[1] = new Book("西游记","吴承恩",38,"小说");
this.bookList[2] = new Book("水浒传","施耐庵",28,"小说");
this.usedSize = 3;
}
}
当然这里获取书籍是用数组下标的方式,因为 usedSize 是用 private 修饰,即又要用get和set方法
public int getUsedSize() {
return usedSize;
}
public void setUsedSize(int usedSize) {
this.usedSize = usedSize;
}
//把书放到pos位置
public void setBookList(int pos,Book book) {
bookList[pos] = book;
}
//获取pos位置的书
public Book getBook(int pos) {
return bookList[pos];
}
//这里本质上是可以写 借阅书籍 等等操作的
3、operation包
用于实现图书管理的基本操作
3.1 IOperation接口
我们将所有的操作都放在operation包里,而且所有的操作都用了IOperation接口,每个操作类里都有work方法进行实现。要根据他们的操作写一个参数为BookList类型的work方法