//Ex1: (passing by object)
class A {
}
class B {
void foo(A a) {
<do something with a>
}
}
//Ex2: (composition)
class C {
A a
void foo(){
<do something with a>
}
}
我的问题是:哪种模式的耦合度较低?哪种模式在现实世界中更受欢迎?
最佳答案
我将尝试解释松散耦合。
- 接口(interface)中的程序,这使得使用在运行时传递实现相同接口(interface)的不同类型的对象成为可能,这里来自不同继承树的类可以实现相同的接口(interface)。
例如:
Animal is the Interface
Dog class implements Animal
Cat class implements Animal
Lion class implements Animal
/////////////////
calling method
/////////////////
callAnimal(new Dog);
/////////////////
called method
/////////////////
public void (Animal a){
// some code
}
将不断变化的行为......封装到抽象类或接口(interface)中,因此当变化来临时很容易,并且由于它是松散耦合的,因此代码中断的可能性较小。
关于java - 哪个模式在java : passing objects to a method or using composition?中耦合度较低,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682573/