编程语言
首页 > 编程语言> > java-了解如何解耦

java-了解如何解耦

作者:互联网

我一直试图在代码中保持低调,但我想我可能还不完全了解它.我的基本理解是,耦合是“依赖类如何相互依赖并了解彼此的行为”.我知道依赖注入是减少耦合和IoC的一种方法.

以下是我提出的一个学生,教授和课程的简单示例.一门课程有学生名单和教授名单.我有一个控制器(使用MVC),可以注入Student和Professor对象.
以下内容是否仍被认为是耦合的或紧密耦合的?这也将是DI的示例,对吗?

学生班

public class Student {
private String firstName;
private String lastName;
private int studentID;
private int address;
private int telephone;
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public int getStudentID() {
    return studentID;
}
public void setStudentID(int studentID) {
    this.studentID = studentID;
}
public int getAddress() {
    return address;
}
public void setAddress(int address) {
    this.address = address;
}
public int getTelephone() {
    return telephone;
}
public void setTelephone(int telephone) {
    this.telephone = telephone;
}
}

教授班

public class Professor {
private String firstName;
private String lastName;
private int professorID;
private int address;
private int telephone;
private int salary;
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public int getProfessorID() {
    return professorID;
}
public void setProfessorID(int professorID) {
    this.professorID = professorID;
}
public int getAddress() {
    return address;
}
public void setAddress(int address) {
    this.address = address;
}
public int getTelephone() {
    return telephone;
}
public void setTelephone(int telephone) {
    this.telephone = telephone;
}
public int getSalary() {
    return salary;
}
public void setSalary(int salary) {
    this.salary = salary;
}
}

课程课程

import java.util.List;

public class Course {
private List<Student> students;
private Professor professor;
public Professor getProfessor() {
    return professor;
}
public void setProfessor(Professor professor) {
    this.professor = professor;
}
public List<Student> getStudents() {
    return students;
}
public void setStudents(List<Student> students) {
    this.students = students;
}

}

解决方法:

我有一个控制器(使用MVC),可以注入Student和Professor对象.以下内容是否仍被认为是耦合的或紧密耦合的?

由于所有引用都是类,因此您具有紧密耦合的设计.一个好的方法是在代码中使用接口.这将允许您随时更改实现,并且不会影响应用程序的其余部分.

这也将是DI的示例,对吗?

如果将您的课程,教授和学生配置为Bean,并且在某个位置指定了在Bean实例化期间如何注入实例的方法,那么它将是一个DI示例.到目前为止,只有三个POJO类.

标签:oop,decoupling,java
来源: https://codeday.me/bug/20191120/2042015.html