在使用对象将对象用作其他对象内的属性(以及对该属性调用方法)与整体耦合良好之间,我感到有些困惑。

这里需要权衡吗?

也许更容易给出不良耦合示例来解释差异(如果存在差异)?

编辑示例:

public class MyClass(){
    MyOtherClass moc;

    public MyClass(MyOtherClass temp){
        moc = temp;
    }

    public void method(){
        moc.call()
    }
}


是由于对组成关系的依赖而导致这种不良耦合吗?如果不是,那么在此示例中耦合会很差。

最佳答案

关联类的两种基本方法是inheritancecomposition。在两个类之间建立继承关系时,您可以利用dynamic bindingpolymorphism

鉴于inheritance关系使得很难更改超类的interface,因此值得研究composition提供的替代方法。事实证明,当您的目标是代码重用时,composition提供了一种产生易于更改的代码的方法。

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

    System.out.println("Peeling is appealing.");
    return 1;
}
}

class Apple extends Fruit {
}

class Example1 {

public static void main(String[] args) {

    Apple apple = new Apple();
    int pieces = apple.peel();
}
}


但是,如果将来希望将peer()的返回值更改为Peel,则即使Example1直接使用Apple且从未明确提及Fruit,您也将破坏Example1代码。

Composition为Apple提供了另一种方式来重用Fruit的peel()实现。 Apple可以保留对Fruit实例的引用,并定义自己的peel()方法,该方法仅对Fruit调用peel(),而不是扩展Fruit。这是代码:

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

    System.out.println("Peeling is appealing.");
    return 1;
}
 }

class Apple {

private Fruit fruit = new Fruit();

public int peel() {
    return fruit.peel();
}
}

class Example2 {

public static void main(String[] args) {

    Apple apple = new Apple();
    int pieces = apple.peel();
}
}


Inheritance相比,Composition具有更高的耦合度。

关于java - 组成与减少耦合?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11409550/

10-09 06:16