优化(解耦),通过面向接口编程和Spring的@Autowired自动装载实现解耦。

1. 常用命名规范

接口定义(IXxx,接口前加I用来区分)

  • service层接口命名:com.xxx.service.IXxxService
  • Dao层接口命名:com.xxx.dao.IXxxDao

实现类的定义(XxxImpl,名称后面加Impl用来区分,放到对应的impl包中)

  • service层接口命名:com.xxx.service.impl.XxxServiceImpl
  • Dao层接口命名:com.xxx.dao.impl. XxxDaoImpl

2. 通过面向接口编程(实现模块解耦)

判断类之间的耦合关系:最简单的办法,就是注释/删除法,将这个类中调用的另一个类,全部注释掉,看看错误处有多少。
在这里插入图片描述

假设有以下类关系

public interface IPersonService{
    
    }//service接口
public class PersonServiceImpl implements IPersonService{
    
    } //service接口的实现类
public class PersonController{
    
    } //controller调用service

3.1 正常调用,controller调用service的实现类

public class PersonController {
    
    

    //直接调用接口的实现类
    PersonServiceImpl personService= new PersonServiceImpl();
    public int findPersonByName(Person person){
    
    
        return personService.findPersonByName(person);
    }
}

查看耦合情况,我们将PersonServiceImpl类注释掉,仅仅只是这几行代码,耦合度就高达三处,肯定是不行的。
在这里插入图片描述

3.2 优化1,通过接口IPersonService来声明对象,实现等号左边解耦

public class PersonController {
    
    

    //通过调用接口来实现等号左边解耦
    IPersonService personService= new PersonServiceImpl();

    public int findPersonByName(Person person) throws InterruptedException {
    
    
        return personService.findPersonByName(person);
    }
}

我们再来通过注释PersonServiceImpl来查看耦合情况,这时候就只有一个耦合了(等号右边耦合)
在这里插入图片描述

3.3 优化2,通过Spring容器注入和自动装载来实现等号右边的解耦

public class PersonController {
    
    

    //通过@Autowired自动装载,它会从容器中找对应类型的bean将其注入赋值给personService
    @Autowired
    IPersonService personService;
    //就相当于执行了 IPersonService personService= new PersonServiceImpl();

    public int findPersonByName(Person person) throws InterruptedException {
    
    
        return personService.findPersonByName(person);
    }
}

继续通过注释PersonServiceImpl来查看是否有耦合情况,没有任何报错,所以没有两个类之间没有耦合了,当前PersonController和PersonService没有耦合了。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40542534/article/details/108977009