在码农港湾
做一个实实在在的内行人

Java 数据访问对象模式

数据访问对象模式或DAO模式将数据访问API与高级业务服务分离。

DAO模式通常具有以下接口和类。

  • 数据访问对象接口定义模型对象的标准操作。
  • 数据访问对象类实现以上接口。可能有多个实现,例如,一个用于数据库,一个用于文件。
  • 模型对象简单的POJO包含get/set方法来存储数据。

例子

import java.util.ArrayList;
import java.util.List;

class Employee {
  private String name;
  private int id;

  Employee(String name, int id) {
    this.name = name;
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }
}

interface EmployeeDao {
  public List<Employee> getAll();

  public Employee get(int id);

  public void updateStudent(Employee student);

  public void delete(Employee student);
}

class EmployeeDaoImpl implements EmployeeDao {
  List<Employee> employeeList;

  public EmployeeDaoImpl() {
    employeeList = new ArrayList<Employee>();
    Employee emp1 = new Employee("Jack", 0);
    Employee emp2 = new Employee("Tom", 1);
    employeeList.add(emp1);
    employeeList.add(emp2);
  }

  @Override
  public void delete(Employee student) {
    employeeList.remove(student.getId());
    System.out.println("Employee: No " + student.getId()
        + ", deleted from database");
  }

  @Override
  public List<Employee> getAll() {
    return employeeList;
  }

  @Override
  public Employee get(int rollNo) {
    return employeeList.get(rollNo);
  }

  @Override
  public void updateStudent(Employee emp) {
    employeeList.get(emp.getId()).setName(emp.getName());
    System.out.println("Emp:No " + emp.getId()
        + ", updated in the database");
  }
}

public class Main {
  public static void main(String[] args) {
    EmployeeDao empDao = new EmployeeDaoImpl();
    for (Employee emp : empDao.getAll()) {
      System.out.println("Emp: [No : " + emp.getId() + ", Name : "
          + emp.getName() + " ]");
    }
    Employee emp = empDao.getAll().get(0);
    emp.setName("Jane");
    empDao.updateStudent(emp);

    empDao.get(0);
    System.out.println("Emp: [No : " + emp.getId() + ", Name : "
        + emp.getName() + " ]");
  }
}

上面的代码生成以下结果。


码农刷题必备工具 VS 码农进阶必读书籍

IT面试宝典宝典書城