一.对案例的思考
所有的代码都在这一个controller文件中,虽然该代码不复杂。但是如果针对大型项目,代码会很复杂。而且不利于项目的维护,复用性差。因此要修改该代码,使其满足维护方便,复用性好的特点。因此要用到一个新的技术,分层解耦。

二.三层架构
在案例代码中,该代码被分为3部分,分别解决数据访问,逻辑处理和接受请求、响应数据的问题。所有的代码都写在了controller类中。而我们在设计软件时,要尽量的让每一个接口、类、方法的功能职责尽可能的单一。这就是单一职责原则。也就是说一个类、接口、方法只负责一件事情。这样会使得我们的类、接口、方法可读性更强,扩展性更好,更利于维护。基于此,在web开发中有了三层架构。

三.应用三层架构的思想改造案例代码
我们访问的数据可能来自xml文件,也可能来自数据库或者是别人提供给我们的接口文件。因此使用面向接口编程的思想可以更好的灵活切换各种模式,便于代码的修改和维护。
dao层接口,实现类
package com.gjw.dao;import com.gjw.pojo.Emp;import java.util.List;public interface EmpDao{public List<Emp> listEmp();
}
package com.gjw.dao.impl;import com.gjw.dao.EmpDao;
import com.gjw.pojo.Emp;
import com.gjw.utils.XmlParserUtils;import java.util.List;public class EmpDaoA implements EmpDao {@Overridepublic List<Emp> listEmp() {String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();System.out.println(file);List<Emp> empList = XmlParserUtils.parse(file, Emp.class);return empList;}
}
service层接口,实现类
package com.gjw.service;import com.gjw.pojo.Emp;import java.util.List;public interface EmpService {public List<Emp> listEmp();
}
package com.gjw.service.impl;import com.gjw.dao.EmpDao;
import com.gjw.dao.impl.EmpDaoA;
import com.gjw.pojo.Emp;
import com.gjw.service.EmpService;import java.util.List;public class EmpServiceA implements EmpService {private EmpDao empDao = new EmpDaoA();@Overridepublic List<Emp> listEmp() {List<Emp> empList = empDao.listEmp();empList.stream().forEach(emp ->{if ("1".equals(emp.getGender())) {emp.setGender("男");} else if ("2".equals(emp.getGender())) {emp.setGender("女");}if ("1".equals(emp.getJob())) {emp.setJob("讲师");} else if ("2".equals(emp.getJob())) {emp.setJob("班主任");} else if ("3".equals(emp.getJob())) {emp.setJob("就业指导");}});return empList;}
}
controller层实现类
package com.gjw.controller;
/*对xml文件进行处理,从而加载处理要响应的数据*/
import com.gjw.pojo.Emp;
import com.gjw.pojo.Result;
import com.gjw.service.EmpService;
import com.gjw.service.impl.EmpServiceA;
import com.gjw.utils.XmlParserUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;@RestController
public class EmpController {private EmpService empService = new EmpServiceA();@RequestMapping("/listEmp")public Result list(){List<Emp> empList = empService.listEmp();return Result.success(empList);}
}

再次启动controller程序,刷新页面,没问题程序正确。

四.总结


