2009-06-12 52 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 
    } 
}