设计模式学习—数据访问对象模式(Data Access Object Design Pattern)

一、我的理解


该模式是将其他形式表现的数据实体(比如存在数据库中的表)转换成编程可用的数据对象的形式。把低级的数据访问 API 或操作从高级的业务服务中分离出来。

二、实现方式


数据访问对象对外提供接口共高级业务获取数据对象,然后底层利用相关技术实现该接口。

三、实例

设计模式学习—数据访问对象模式(Data Access Object Design Pattern)_第1张图片
Java实例

Student类:转换后的数据对象类

package com.study.dp.dao;

public class Student {

    private String name;
    private int rollNo;
    
    public Student(String name, int rollNo) {
        super();
        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;
    }

}
StudentDao类:数据访问接口,供高级业务调用数据

package com.study.dp.dao;

import java.util.List;

public interface StudentDao {

    public List getAllStudents();
    public Student getStudent(int rollNo);
    public void updateStudent(Student student);
    public void deleteStudent(Student student);
    
}
StudentDaoImpl类:具体实现方式

package com.study.dp.dao;

import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {

    // 列表当做数据库
    List 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 List 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");
        
    }

    @Override
    public void deleteStudent(Student student) {
        students.remove(student.getRollNo());
        System.out.println("Student: Roll No "+student.getRollNo()+", deleted from database");
    }

}
Demo类:测试用类

package com.study.dp.dao;

public class Demo {

    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() + " ]");
    }

}


四、应用场景



你可能感兴趣的:(设计模式)