2009-06-12 29 views
0

我知道關於關聯和聚集以及構成和泛化的定義。繼承是「是」的關係,構成是「有」的關係。如何根據編程代碼顯示聚合?

Class A { 
} 

Class B extends A { // this is Generalization 
} 

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

現在我的問題是如何根據編程代碼顯示聚集和簡單的關聯。 ?

回答

1

我懷疑你的真正問題與組合與聚合有關。您可以考慮所有權方面的差異,但真正的區別(對於我的資金)是控制聚合對象生命週期的因素。

In composition。當組合對象被銷燬時,它所包含的部分或類將隨着它被銷燬。通過聚合,包含對象的生命週期可以獨立於包含對象。在代碼中。這歸結爲組件對象是由值還是由引用指定。聚合具有通過引用(或者如在示例中的指針)完成。如果按值完成,則組件部分將超出範圍並被包含對象銷燬,因此是組合。

因此,在這種情況下,引擎是組合的一個例子,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; 

} 

道歉,如果這是不是最好的例子,但希望它說明了要點。

0

我不知道你要什麼了這裏,但我建議下面的例子:

聚集

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 
    } 
}