數(shù)據(jù)訪問對象模式(Data Access Object Pattern)或 DAO 模式用于把低級的數(shù)據(jù)訪問 API 或操作從高級的業(yè)務(wù)服務(wù)中分離出來。以下是數(shù)據(jù)訪問對象模式的參與者。
我們將創(chuàng)建一個作為模型對象或數(shù)值對象的 Student 對象。StudentDao 是數(shù)據(jù)訪問對象接口。StudentDaoImpl 是實現(xiàn)了數(shù)據(jù)訪問對象接口的實體類。DaoPatternDemo,我們的演示類使用 StudentDao 來演示數(shù)據(jù)訪問對象模式的用法。
創(chuàng)建數(shù)值對象。
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)建實現(xiàn)了上述接口的實體類。
StudentDaoImpl.java
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
//列表是當(dāng)作一個數(shù)據(jù)庫
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");
}
//從數(shù)據(jù)庫中檢索學(xué)生名單
@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ù)訪問對象模式的用法。
CompositeEntityPatternDemo.java
public class DaoPatternDemo {
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()+" ]");
}
}
驗證輸出。
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]
更多建議: