數(shù)據(jù)訪問對象模式或DAO模式用于將低級數(shù)據(jù)訪問API或操作與高級業(yè)務(wù)服務(wù)分離。 以下是數(shù)據(jù)訪問對象模式的參與者。
get/set
方法。在這個將創(chuàng)建一個作為Model
或Value
對象的Student
對象。 StudentDao
是數(shù)據(jù)訪問對象接口。 StudentDaoImpl
是實(shí)現(xiàn)數(shù)據(jù)訪問對象接口的具體類。 DaoPatternDemo這是一個演示類,將使用StudentDao
演示使用數(shù)據(jù)訪問對象模式。
數(shù)據(jù)訪問對象模式示例的結(jié)構(gòu)如下圖所示 -
創(chuàng)建值對象,其代碼如下 -
Student.java
public class Student {
private String name;
private int rollNo;
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ù)訪問對象接口,其代碼如下 -
StudentDao.java
import java.util.List;
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)上面的接口的具體類,其代碼如下 -
StudentDaoImpl.java
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
//list is working as a database
List<Student> students;
public StudentDaoImpl(){
students = new ArrayList<Student>();
Student student1 = new Student("Robert",0);
Student student2 = new Student("John",1);
students.add(student1);
students.add(student2);
}
@Override
public void deleteStudent(Student student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
}
//retrive list of students from the database
@Override
public List<Student> getAllStudents() {
return students;
}
@Override
public Student getStudent(int rollNo) {
return students.get(rollNo);
}
@Override
public void updateStudent(Student student) {
students.get(student.getRollNo()).setName(student.getName());
System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the database");
}
}
使用StudentDao
演示數(shù)據(jù)訪問對象模式的使用。
DaoPatternDemo.java
public class DaoPatternDemo {
public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();
//print all students
for (Student student : studentDao.getAllStudents()) {
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
}
//update student
Student student =studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
//get the student
studentDao.getStudent(0);
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
}
}
驗(yàn)證輸出,執(zhí)行上面的代碼得到以下結(jié)果 -
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]