📅  最后修改于: 2023-12-03 14:54:57.883000             🧑  作者: Mango
数据访问对象模式(Data Access Object Pattern)是一种在软件工程中应用广泛的设计模式。它的主要目的是将数据持久化及数据存储逻辑与业务逻辑分离。DAOP的目标是隐藏数据访问逻辑,以便做出更改而不需要修改架构。
数据访问对象模式由以下几个部分组成:
实现一个简单的DAO示例。
public interface StudentDao {
List<Student> getAllStudents();
Student getStudent(int rollNo);
void updateStudent(Student student);
void deleteStudent(Student student);
}
public class StudentDaoImpl implements StudentDAO {
List<Student> students;
public StudentDaoImpl(){
students = new ArrayList<>();
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 " + student.getName() + " is removed 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 " + student.getRollNo() + " is updated in the database");
}
}
public class DataAccessObjectPatternDemo {
public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();
//输出所有的学生
for (Student student : studentDao.getAllStudents()) {
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
}
// 更新学生
Student student = studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
//获取学生
studentDao.getStudent(0);
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
}
}
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;
}
}
在上面的代码示例中,我们实现了一个简单的DAO接口,定义了增删改查的常见方法,供Student类使用。这个简单的示例展示了如何使用数据访问对象模式。