DAO模式代码阅读及应用

  1. StudenDaoListImpl.javaStudentDaoArrayImpl.java是两个不同的实现类,它们实现了StudentDao接口。它们的不同之处在于数据存储的方式不同。StudenDaoListImpl使用ArrayList作为底层数据结构,而StudentDaoArrayImpl使用数组作为底层数据结构。

  2. StudentDao.java是一个接口,它定义了对学生信息进行操作的方法,如添加学生、根据姓名获取学生等。接口中没有实现代码是因为接口只定义了方法的签名,具体的实现由实现类来完成。

  3. 其中对我启发最大的一句话是:"DAO模式将数据访问逻辑与业务逻辑分离,提高了代码的可维护性和可测试性"。这句话强调了DAO模式的优点,即将数据访问逻辑与业务逻辑分离,使得代码更易于维护和测试。

  4. 运行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();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值