数据访问对象模式(Data Access Object Pattern)

即不直接通过数据对象,而是抽象成Dao层来做这个事情。

数据访问对象模式的实例

定义数据模型

  1. class Student {
  2. constructor(name, rollNo){
  3. this.name = name;
  4. this.rollNo = rollNo;
  5. }
  6. getName() {
  7. return this.name;
  8. }
  9. setName(name) {
  10. this.name = name;
  11. }
  12. getRollNo() {
  13. return this.rollNo;
  14. }
  15. setRollNo(rollNo) {
  16. this.rollNo = rollNo;
  17. }
  18. }

Dao层的实现

  1. class StudentDao{
  2. constructor(){
  3. this.students = [];
  4. this.students.getIndexByRollNo = (rollNo)=>{
  5. return this.students.findIndex(
  6. (val)=>val.getRollNo() == rollNo
  7. );
  8. }
  9. const student1 = new Student("Robert",0);
  10. const student2 = new Student("John",1);
  11. this.students.push(student1);
  12. this.students.push(student2);
  13. }
  14. deleteStudent(student) {
  15. this.students.splice(student.getIndexByRollNo(student.getRollNo() ),1);
  16. console.log("Student: Roll No " + student.getRollNo()
  17. +", deleted from database");
  18. }
  19. //从数据库中检索学生名单
  20. getAllStudents() {
  21. return this.students;
  22. }
  23. getStudent(rollNo) {
  24. return this.students[this.students.getIndexByRollNo(rollNo)];
  25. }
  26. updateStudent(student) {
  27. this.students[this.students.getIndexByRollNo(student.getRollNo())].setName(student.getName());
  28. console.log("Student: Roll No " + student.getRollNo()
  29. +", updated in the database");
  30. }
  31. }

使用Dao操作数据

  1. const studentDao = new StudentDao();
  2. //输出所有的学生
  3. for (let student of studentDao.getAllStudents()) {
  4. console.log("Student: [RollNo : "
  5. +student.getRollNo()+", Name : "+student.getName()+" ]");
  6. }
  7. //更新学生
  8. const student =studentDao.getAllStudents()[studentDao.getAllStudents().getIndexByRollNo(0)];
  9. student.setName("Michael");
  10. studentDao.updateStudent(student);
  11. //获取学生
  12. studentDao.getStudent(0);
  13. console.log("Student: [RollNo : "
  14. +student.getRollNo()+", Name : "+student.getName()+" ]");

数据访问对象模式的优势

数据层和操作层分离,结构清晰,层级稳定。这看起来像是一种失血模型。