私は、関連付けと集約、構成と一般化について、それらが定義上何であるかを知っています。継承は「ある」関係であり、合成は「ある」関係です。
Class A {
}
Class B extends A { // this is Generalization
}
Class C {
A ob; // this is composition
}
今私の質問は、プログラミングコードの観点から、集約と単純な関連付けがどのように表示されるかです。?
私は、関連付けと集約、構成と一般化について、それらが定義上何であるかを知っています。継承は「ある」関係であり、合成は「ある」関係です。
Class A {
}
Class B extends A { // this is Generalization
}
Class C {
A ob; // this is composition
}
今私の質問は、プログラミングコードの観点から、集約と単純な関連付けがどのように表示されるかです。?
あなたの本当の質問は、構成と集約に関係していると思います。所有権の観点から違いを考えることができますが、(私のお金で言えば) 本当の違いは、集約されたオブジェクトのライフサイクルを制御するものです。
構成中。構成されたオブジェクトが破棄されると、それに含まれるパーツまたはクラスも一緒に破棄されます。集約を使用すると、含まれるオブジェクトの存続期間を、含まれるオブジェクトから独立させることができます。コードで。これは、コンポーネント オブジェクトが値または参照のどちらで指定されているかにかかっています。集計は、参照 (または例のようにポインター) によって行う必要があります。値によって行われる場合、コンポーネント部分はスコープ外になり、オブジェクトを含むと破棄されるため、合成になります。
したがって、この場合、Engine は構成の例で、Battery は集約の例です。
#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;
}
これが最良の例ではない場合は申し訳ありませんが、うまくいけば要点を示しています。
I'm not sure exactly what you're going for here, but I would suggest the following examples:
Aggregation
public class A { }
public class List<A> { } // aggregation of A
Association (uses)
public class A
{
public void AMethod() { ... }
public class B
{
public void BMethod( A a )
{
a.AMethod(); // B uses A
}
}