分层-三层架构
文章目录
- 介绍
- 代码拆分
- Dao层
- server层
- controller层
- 运行结果
介绍
在我们进行程序设计以及程序开发时,尽可能让每一个接口、类、方法的职责更单一些(单一职责原则)。
单一职责原则:一个类或一个方法,就只做一件事情,只管一块功能。这样就可以让类、接口、方法的复杂度更低,可读性更强,扩展性更好,也更利于后期的维护。
从组成上看可以分为三个部分:
- 数据访问:负责业务数据的维护操作,包括增、删、改、查等操作。
- 逻辑处理:负责业务逻辑处理的代码。
- 请求处理、响应数据:负责,接收页面的请求,给页面响应数据。
按照上述的三个组成部分,在我们项目开发中呢,可以将代码分为三层:
- Controller:控制层。接收前端发送的请求,对请求进行处理,并响应数据。
- Service:业务逻辑层。处理具体的业务逻辑。
- Dao:数据访问层(Data Access Object),也称为持久层。负责数据访问操作,包括数据的增、删、改、查。
三层架构的程序执行流程:
- 前端发起的请求,由Controller层接收(Controller响应数据给前端)
- Controller层调用Service层来进行逻辑处理(Service层处理完后,把处理结果返回给Controller层)
- Serivce层调用Dao层(逻辑处理过程中需要用到的一些数据要从Dao层获取)
- Dao层操作文件中的数据(Dao拿到的数据会返回给Service层)
代码拆分
Dao层
创建UserDao接口
package com.example.Dao;import java.util.List;public interface UserDao {/*** 加载用户数据* @return*/public List<String> findAll();
}
创建UserDaoImpl接口,实现文件操作
package com.example.Dao.impl;import cn.hutool.core.io.IoUtil;
import com.example.Dao.UserDao;import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;public class UserDaoImpl implements UserDao {@Overridepublic List<String> findAll() {//加载并读取user.txtInputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());return lines;}
}
server层
创建UserSerivce接口
package com.example.service;import com.example.pojo.User;import java.util.List;public interface UserService {/*** 查询所有用户信息* @return*/public List<User> findAll();
}
创建UserSerivceImpl接口,实现数据操作,返回对象
package com.example.service.impl;import com.example.Dao.UserDao;
import com.example.Dao.impl.UserDaoImpl;
import com.example.pojo.User;
import com.example.service.UserService;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;public class UserServiceImpl implements UserService {private UserDao userDao = new UserDaoImpl();@Overridepublic List<User> findAll() {//调用Dao获取数据List<String> lines = userDao.findAll();//解析用户信息,封装List<User> userList = lines.stream().map(line -> {String[] parts = line.split(",");Integer id = Integer.parseInt(parts[0]);String username = parts[1];String password = parts[2];String name = parts[3];Integer age = Integer.parseInt(parts[4]);LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));return new User(id, username, password, name, age, updateTime);}).toList();//返回return userList;}
}
controller层
创建UserController类
@RestController
public class UserController {private UserService userService = new UserServiceImpl();@RequestMapping("/list")public List<User> list() throws Exception{List<User> userList = userService.findAll();//返回json数据return userList;}
}
运行结果
目录
运行并访问