[Design Pattern] DAO Pattern 简单案例
Data Access Object Pattern, or DAO Pattern, 即 DAO 模式,用于分离底层的数据访问接口,已经上层的业务逻辑。
下面是 Dao 模式的一个简单的案例。
Student 是纯 Java Beans 类。StudentDao 定义 Dao 的访问接口,StudentDaoImpl 实现该接口。 DaoPatternDemo 演示 Dao 模式
代码实现
Student ,是纯数据对象
public class Student implements Cloneable { 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 String toString(){ return "[name : " + name + ", rollNo : " + rollNo + "]"; } public Object clone() { Student newStud = new Student(this.name, this.rollNo); return newStud; } }
StudentDao 定义 Dao 接口
import java.util.List; public interface StudentDao { public List<Student> getAllStudents(); public void updateStudent(Student student); public void deleteStudent(Student student); public void addStudent(Student student); }
StudentDaoImpl 是 Dao 的具体类,实现 Dao 接口
import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; public class StudentDaoImpl implements StudentDao { private Map<Integer, Student> no_stud; public StudentDaoImpl(){ no_stud = new Hashtable<Integer, Student>(); Student studa = new Student("aa", 0); Student studb = new Student("bb", 1); no_stud.put(studa.getRollNo(), studa); no_stud.put(studb.getRollNo(), studb); } @Override public List<Student> getAllStudents() { List<Student> students = new LinkedList<>(no_stud.values()); return students; } @Override public void updateStudent(Student student) { no_stud.get(student.getRollNo()).setName(student.getName()); } @Override public void deleteStudent(Student student) { no_stud.remove(student.getRollNo()); } @Override public void addStudent(Student student) { if (no_stud.containsKey(student.getRollNo())){ System.out.println(" duplicate student No. cannot add "); } else{ no_stud.put(student.getRollNo(), student); } } public Student getFirstStudentCopy(){ Student student = (Student)no_stud.get(0).clone(); return student; } }
演示 Dao 模式。注,代码中 StudentDaoImpl::getFirstStudentCopy ,是为了演示 StudentDaoImpl::updateStudent 而出现的 ,但并未出现在 UML 图中。
public class DaoPatternDemo { public static void main(){ StudentDaoImpl studentDaoImpl = new StudentDaoImpl(); System.out.println(studentDaoImpl.getAllStudents()); Student student = studentDaoImpl.getFirstStudentCopy(); student.setName("sss"); System.out.println(studentDaoImpl.getAllStudents()); studentDaoImpl.updateStudent(student); System.out.println(studentDaoImpl.getAllStudents()); } }
参考资料
Data Access Object Pattern, TutorialsPoint