zno2

29) Data Access Object Pattern

类别:

 

问题:

 

方案:

 

 

 

示例:

 

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

public class DataAccessObjectPattern {
    public static void main(String[] args) {
        StudentDao studentDao = new StudentDaoImpl();
        // print all students
        for (Student student : studentDao.getAllStudents()) {
            System.out.println("show all: [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("show one: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
    }

}

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;
    }
}

interface StudentDao {
    public List<Student> getAllStudents();

    public Student getStudent(int rollNo);

    public void updateStudent(Student student);

    public void deleteStudent(Student student);
}

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("update one: Roll No " + student.getRollNo() + ", updated in the database");
    }
}

 

show all: [RollNo : 0, Name : Robert ]
show all: [RollNo : 1, Name : John ]
update one: Roll No 0, updated in the database
show one: [RollNo : 0, Name : Michael ]

 

应用:

 

不足:(

 

优化:)

 

posted on 2023-06-16 16:57  zno2  阅读(7)  评论(0编辑  收藏  举报

导航