2012-07-10 119 views
0

我在使用對象作爲其他對象內的屬性(以及在屬性上調用方法)之間使用組合,而不是具有良好的整體耦合之間有點混淆。組合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

回答

1

兩種基本方法是。當你建立兩個類之間的繼承關係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

1

而是壞/良好的耦合的,好像最接受的條件是緊/鬆耦合的,優選鬆散耦合的對象。在你的榜樣,更緊密的耦合可以是這樣的(與插圖添加的功能):

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進行更改。