-
StudenDaoListImpl.java
和StudentDaoArrayImpl.java
是两个不同的实现类,它们实现了StudentDao
接口。它们的不同之处在于数据存储的方式不同。StudenDaoListImpl
使用ArrayList
作为底层数据结构,而StudentDaoArrayImpl
使用数组作为底层数据结构。 -
StudentDao.java
是一个接口,它定义了对学生信息进行操作的方法,如添加学生、根据姓名获取学生等。接口中没有实现代码是因为接口只定义了方法的签名,具体的实现由实现类来完成。 -
其中对我启发最大的一句话是:"DAO模式将数据访问逻辑与业务逻辑分离,提高了代码的可维护性和可测试性"。这句话强调了DAO模式的优点,即将数据访问逻辑与业务逻辑分离,使得代码更易于维护和测试。
-
运行
Test.java
时,根据注释修改相应代码可以选择使用数组或列表实现学生信息的存储和访问。使用DAO模式的好处是将数据访问逻辑与业务逻辑分离,使得后续的扩展和维护更加方便。通过使用接口和实现类的方式,可以在不修改业务逻辑的情况下,轻松切换不同的数据存储方式。
package shoppingcart;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FileCartDao implements CartDao {
private String filePath;
public FileCartDao(String filePath) {
this.filePath = filePath;
}
@Override
public List<Item> getAllItems() {
List<Item> items = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
String name = parts[0];
double price = Double.parseDouble(parts[1]);
int quantity = Integer.parseInt(parts[2]);
Item item = new Item(name, price, quantity);
items.add(item);
}
} catch (IOException e) {
e.printStackTrace();
}
return items;
}
@Override
public void addItem(Item item) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
String line = item.getName() + "," + item.getPrice() + "," + item.getQuantity();
writer.write(line);
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}