组合vs减少耦合?

组合vs减少耦合?

问题描述:

我在使用对象作为其他对象内的属性(以及在属性上调用方法)之间使用组合,而不是具有良好的整体耦合之间有点混淆。组合vs减少耦合?

这里有一个权衡吗?

也许坏耦合其更容易让例子来说明两者的区别(如果是有区别的)?

EDIT例如:

public class MyClass(){ 
    MyOtherClass moc; 

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

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

是这种不良耦合,因为该组合物的关系的依赖的??如果不是,在这个例子中,耦合不好。对涉及类

+0

什么是“良好的整体耦合”?一般来说,几乎任何类型的耦合都是不可取的。 – 2012-07-10 08:40:46

+0

你为什么不举一些例子? – Nick 2012-07-10 08:46:16

+0

用示例编辑 – mezamorphic 2012-07-10 09:14:46

两种基本方法是。当你建立两个类之间的继承关系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(); 
} 
} 

如果在未来的某个时刻,但是,你想改变剥离的返回值()输入Peel,你会打破例1码的代码,即使例1直接使用苹果从未明确提到水果。

Composition为Apple重新使用Fruit的peel()实现提供了另一种方法。相反,延长水果,苹果可以装到Fruit实例的引用和定义自己的peel()方法只需在水果调用peel()。下面的代码:

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更高的耦合。

+0

我在几个眼前看过那个例子,我理解继承“传播”错误的危险。那么使用合成就可以了,这种技术并不是很糟糕的耦合? – mezamorphic 2012-07-10 09:15:42

+0

@Porcupine它取决于你的要求,如果两个对象真的耦合,那么你不能避免它,但是组合优于继承。 – amicngh 2012-07-10 09:29:51

+0

所以正常的耦合不是一个“邪恶”,它只是纯粹主义者讨厌的东西之一? – mezamorphic 2012-07-10 09:48:54

而是坏/良好的耦合的,好像最接受的条件是紧/松耦合的,优选松散耦合的对象。在你的榜样,更紧密的耦合可以是这样的(与插图添加的功能):

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

    public void method() 
    { 
     for (int i = 0; i < moc.items.Count; i++) 
     { 
      moc.items[i].Price += 5; 
     } 
    } 
} 

这里,MyClass的取决于MyOtherClass(项目列表,成本等实施的具体实施细则..)。处理这种情况的更松散耦合的方法是将该逻辑移到MyOtherClass上的函数中。这样,MyOtherClass的所有实现细节都从MyClass隐藏起来,并且可以独立于MyClass进行更改。