1

構成を使用してオブジェクトを他のオブジェクト内の属性として使用する (および属性に対してメソッドを呼び出す) ことと、全体的な結合を良好にすることとの間で少し混乱しています。

ここにトレードオフはありますか?

おそらく、違いを説明するために悪い結合の例を挙げた方が簡単でしょうか(違いがある場合)?

編集例:

public class MyClass(){
    MyOtherClass moc;

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

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

これは組成関係に依存してカップリングが悪いのでしょうか?? そうでない場合、この例で悪い結合とは何でしょうか。

4

2 に答える 2

2

悪い/良い結合の代わりに、最も受け入れられている用語は密結合/疎結合であり、疎結合オブジェクトが好まれているようです。あなたの例では、より緊密な結合は次のようになります(説明用の機能が追加されています):

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 とは独立して変更できます。

于 2012-07-12T18:53:43.973 に答える
2

クラスを関連付ける 2 つの基本的な方法はinheritance、 とcompositionです。2 つのクラス間に継承関係を確立すると、 と を利用できdynamic bindingますpolymorphism

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() の戻り値を type に変更したい場合はPeel、Example1 が Apple を直接使用し、Fruit について明示的に言及していなくても、Example1 コードのコードを壊すことになります。

CompositionApple が Fruit の の実装を再利用するための代替方法を提供しますpeel()。Fruit を拡張する代わりに、Apple はインスタンスへの参照を保持し、単にFruitを呼び出す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

于 2012-07-10T09:13:09.243 に答える