Java design pattern - Data Access Object Pattern
The data access object pattern or DAO pattern separates the data access API from advanced business services. DAO patterns typically have the following interfaces and classes. The data provider interface defines standard operations for model objects. The data access object class implements the above interfaces. There may be multiple implementations, for example, one for the database and one for the file. The simple POJO of the model object contains the get/set method to store the data.
import java.util.ArrayList;
import java.util.List;
class Employee {
private String name;
private int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
interface EmployeeDao {
public List<Employee> getAll();
public Employee get(int id);
public void updateStudent(Employee student);
public void delete(Employee student);
}
class EmployeeDaoImpl implements EmployeeDao {
List<Employee> employeeList;
public EmployeeDaoImpl() {
employeeList = new ArrayList<Employee>();
Employee emp1 = new Employee("Jack", 0);
Employee emp2 = new Employee("Tom", 1);
employeeList.add(emp1);
employeeList.add(emp2);
}
@Override
public void delete(Employee student) {
employeeList.remove(student.getId());
System.out.println("Employee: No " + student.getId()
+ ", deleted from database");
}
@Override
public List<Employee> getAll() {
return employeeList;
}
@Override
public Employee get(int rollNo) {
return employeeList.get(rollNo);
}
@Override
public void updateStudent(Employee emp) {
employeeList.get(emp.getId()).setName(emp.getName());
System.out.println("Emp:No " + emp.getId()
+ ", updated in the database");
}
}
public class Main {
public static void main(String[] args) {
EmployeeDao empDao = new EmployeeDaoImpl();
for (Employee emp : empDao.getAll()) {
System.out.println("Emp: [No : " + emp.getId() + ", Name : "
+ emp.getName() + " ]");
}
Employee emp = empDao.getAll().get(0);
emp.setName("Jane");
empDao.updateStudent(emp);
empDao.get(0);
System.out.println("Emp: [No : " + emp.getId() + ", Name : "
+ emp.getName() + " ]");
}
}
Result
Reprinted address
https://www.w3cschool.cn/java/java-data-access-object-pattern.html