數(shù)據(jù)訪問對象模式(Data Access Object Pattern)或 DAO 模式用于把低級的數(shù)據(jù)訪問 API 或操作從高級的業(yè)務(wù)服務(wù)中分離出來。以下是數(shù)據(jù)訪問對象模式的參與者。
- 數(shù)據(jù)訪問對象接口(Data Access Object Interface) - 該接口定義了在一個(gè)模型對象上要執(zhí)行的標(biāo)準(zhǔn)操作。
- 數(shù)據(jù)訪問對象實(shí)體類(Data Access Object concrete class) - 該類實(shí)現(xiàn)了上述的接口。該類負(fù)責(zé)從數(shù)據(jù)源獲取數(shù)據(jù),數(shù)據(jù)源可以是數(shù)據(jù)庫,也可以是 xml,或者是其他的存儲(chǔ)機(jī)制。
- 模型對象/數(shù)值對象(Model Object/Value Object) - 該對象是簡單的 POJO,包含了 get/set 方法來存儲(chǔ)通過使用 DAO 類檢索到的數(shù)據(jù)。
- 創(chuàng)建數(shù)值對象。
/**
* 1. 創(chuàng)建數(shù)值對象。
* @author mazaiting
*/
public class Student {
private String name;
private int rollNo;
public Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
- 創(chuàng)建數(shù)據(jù)訪問對象接口。
/**
* 2. 創(chuàng)建數(shù)據(jù)訪問對象接口。
* @author mazaiting
*/
public interface StudentDao {
public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}
- 創(chuàng)建實(shí)現(xiàn)了上述接口的實(shí)體類。
/**
* 3. 創(chuàng)建實(shí)現(xiàn)了StudentDao接口的實(shí)體類。
* @author mazaiting
*/
public class StudentDaoImpl implements StudentDao{
List<Student> students;
public StudentDaoImpl(){
students = new ArrayList<Student>();
Student student1 = new Student("Rebert", 0);
Student student2 = new Student("John", 1);
students.add(student1);
students.add(student2);
}
public List<Student> getAllStudents() {
return students;
}
public Student getStudent(int rollNo) {
return students.get(rollNo);
}
public void updateStudent(Student student) {
students.get(student.getRollNo()).setName(student.getName());
System.out.println("Student: Roll No " + student.getRollNo()
+", updated in the database");
}
public void deleteStudent(Student student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo()
+", deleted from database");
}
}
- 使用 StudentDao 來演示數(shù)據(jù)訪問對象模式的用法。
/**
* 4. 使用 StudentDao 來演示數(shù)據(jù)訪問對象模式的用法。
* @author mazaiting
*/
public class Client {
public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();
// 輸出所有的學(xué)生
for (Student student : studentDao.getAllStudents()) {
System.out.println("Student: [RollNo : "
+student.getRollNo()+", Name : "+student.getName()+" ]");
}
// 更新學(xué)生
Student student = studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
// 獲取學(xué)生
studentDao.getStudent(0);
System.out.println("Student: [RollNo : "
+student.getRollNo()+", Name : "+student.getName()+" ]");
}
}
- 打印結(jié)果
Student: [RollNo : 0, Name : Rebert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]