Java 數(shù)據(jù)訪問對象模式

2018-01-17 18:55 更新

Java設(shè)計(jì)模式 - 數(shù)據(jù)訪問對象模式


數(shù)據(jù)訪問對象模式或DAO模式將數(shù)據(jù)訪問API與高級(jí)業(yè)務(wù)服務(wù)分離。

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

  • 數(shù)據(jù)訪問對象接口定義模型對象的標(biāo)準(zhǔn)操作。

  • 數(shù)據(jù)訪問對象類實(shí)現(xiàn)以上接口。可能有多個(gè)實(shí)現(xiàn),例如,一個(gè)用于數(shù)據(jù)庫,一個(gè)用于文件。

  • 模型對象簡單的POJO包含get/set方法來存儲(chǔ)數(shù)據(jù)。

例子

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() + " ]");
  }
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)