紧耦合和松耦合
Tight and loose coupling
谁能解释一下为什么第一段代码紧耦合而另一段代码松耦合?
// tightly coupled
class Employee {
Address address;
Employee(){
address=new Address();
}
}
//loosely coupled
class Employee {
Address address;
Employee(Address address){
this.address=address;
}
}
Employee class 需要一个 Address,所以 Address 是 Employee 的依赖项。
// tightly coupled
class Employee {
Address address;
Employee(){
address=new Address();
}
}
在第一种情况下,Employee 负责创建 Address 的实例,因此 Employee 与 Address 紧密耦合。
//loosely coupled
class Employee {
Address address;
Employee(Address address){
this.address=address;
}
}
第二种情况Address会在外部给Employee,所以Employee和Address没有紧耦合。
举个例子。这里我们有两个 Address
的实现,即 HomeAddress
和 WorkAddress
。由于在第一种情况下 Employee
负责实例化 Address
,因此它与家庭地址或工作地址紧密耦合。但是,在第二种情况下,Employee
class 可以使用任何已提供给它的 Address
。
谁能解释一下为什么第一段代码紧耦合而另一段代码松耦合?
// tightly coupled
class Employee {
Address address;
Employee(){
address=new Address();
}
}
//loosely coupled
class Employee {
Address address;
Employee(Address address){
this.address=address;
}
}
Employee class 需要一个 Address,所以 Address 是 Employee 的依赖项。
// tightly coupled
class Employee {
Address address;
Employee(){
address=new Address();
}
}
在第一种情况下,Employee 负责创建 Address 的实例,因此 Employee 与 Address 紧密耦合。
//loosely coupled
class Employee {
Address address;
Employee(Address address){
this.address=address;
}
}
第二种情况Address会在外部给Employee,所以Employee和Address没有紧耦合。
举个例子。这里我们有两个 Address
的实现,即 HomeAddress
和 WorkAddress
。由于在第一种情况下 Employee
负责实例化 Address
,因此它与家庭地址或工作地址紧密耦合。但是,在第二种情况下,Employee
class 可以使用任何已提供给它的 Address
。