質問

私は、彼らは、定義により何であるかを協会との集約とコンポジションと汎化について知っています。継承はある関係および組成物である関係「がある」「さ」。

Class A {
}

Class B extends A { // this is Generalization
}

Class C {
 A ob;  // this is composition
}

は、今、私の質問は、集約し、シンプルな協会はプログラミングコードの面で示されている方法です。 ?

役に立ちましたか?

解決

私はあなたの本当の問題は、集約対組成物と関係している疑いがあります。あなたが集約されたオブジェクトのライフサイクルを制御するものである所有権の条項が、(私のお金のための)本当の区別の違いを考えることができます。

組成物において。構成オブジェクトが破棄された場合、その含有部分またはクラスはそれと一緒に破壊されます。凝集に、含まれるオブジェクトの寿命が含まれているオブジェクトから独立していることができます。コードでは。これは、コンポーネントオブジェクトが値または参照により指定されているかどうかに帰着します。集合が(例のように、またはポインタ)参照することによって行われなければなりません。それは値によって行われる場合に構成部品がスコープ外に移動し、オブジェクトを含有する破壊され、したがって、組成物である。

したがって、この場合のエンジンは、組成物およびバッテリー集約の例の一例である。

#include <iostream>

using namespace std;

class Engine
{
   public:

      Engine() {cout << "Engine created\n";};
     ~Engine() {cout << "Engine destroyed\n";};
};


class Battery
{
   public:

      Battery() {cout << "Battery created\n\n";};
     ~Battery() {cout << "\nBattery destroyed\n";};
};

class Car
{
   private:

      Battery *bat;
      Engine  eng;  //Engine will go out of scope with Car

   public:

      Car(Battery* b) : bat(b) {cout << "Car created\n";};
     ~Car() {cout << "Car destroyed\n";};

       void drive(int miles) {/*...*/};
};



int main(int argc, char *argv[])
{
   //a Battery lifecycle exists independently of a car
   Battery* battery = new Battery();

   //but a car needs to aggregate a Battery to run
   Car* car1 = new Car(battery);

   car1->drive(5);

   //car1 and its Engine destroyed but not the Battery
   delete car1;

   cout << "---------------\n";

   //new car, new composed Engine, same old Battery
   Car* car2 = new Car(battery);

   car2->drive(5);
   delete car2;

   //destroy battery independently of the cars
   delete battery;

}

謝罪これが最良の例ではないですが、うまくいけば、それは主なポイントを示します。

場合

他のヒント

私はあなたがここのために行っている正確にわからないんだけど、私は次の例をお勧めします:

集計

public class A { }
public class List<A> { }  // aggregation of A

協会(用途)

public class A
{
    public void AMethod() { ... }

public class B
{
    public void BMethod( A a )
    {
         a.AMethod();  // B uses A
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top