天天看點

設計模式中類的關系之聚合關系(Aggregation)

      聚合關系是關聯關系的一種特例,它展現的是整體與部分的關系,即has-a的關系,此時整體與部分之間是可分離的,它們可以具有各自的生命周期,部分可以屬于多個整體對象,也可以為多個整體對象共享。比如計算機與CPU、公司與員工的關系等。表現在代碼層面,和關聯關系是一緻的,隻能從語義級别來區分。

      在聚合關系中,成員類是整體類的一部分,即成員對象是整體對象的一部分,但是成員對象可以脫離整體對象獨立存在。在UML中,聚合關系用帶空心菱形的直線表示。

      UML示例圖如下所示:

設計模式中類的關系之聚合關系(Aggregation)

      示例代碼如下(概要,完整源碼見附件):

      Computer.m檔案

1 #import "Computer.h"
 2 
 3 @implementation Computer
 4 @synthesize centralProcessingUnit = _centralProcessingUnit;
 5 
 6 - (id)initWithCpu:(CentralProcessingUnit *)cpu
 7 {
 8     self = [super init];
 9     
10     if (self != nil)
11     {
12         self.centralProcessingUnit = cpu;
13     }
14     return self;
15 }
16 
17 - (void)dealloc
18 {
19     [_centralProcessingUnit release];
20     
21     NSLog(@"Computer dealloc");
22     
23     [super dealloc];
24 }
25 
26 @end      

      調用代碼:

1         CentralProcessingUnit *centralProcessingUnit = [[CentralProcessingUnit alloc] init];
 2         
 3         Computer *computer = [[Computer alloc] initWithCpu:centralProcessingUnit];
 4         
 5         // computer生命周期結束
 6         [computer release];
 7         
 8         // centralProcessingUnit還可以進行其他操作.....
 9         
10         [centralProcessingUnit release];      

      從調用代碼我們可以看到,我們建立了一個獨立的centralProcessingUnit對象,然後将這個對象傳入了Computer的init函數。當computer對象生命周期結束的時候,centralProcessingUnit對象如果還有其他指向它的引用,是可以繼續存在的。也就是說,它們的生命周期是相對獨立的。

      源碼下載下傳   傳回目錄

循自然之道,撫浮躁之心