Composite Object
2011/03/04 10:06
瀏覽631
迴響0
推薦1
引用0
Composite Object,是物件導向程式簡化程式碼的寫法,使用的非常多。
如果一個物件的類別繼承了10個以上的subclass,那麼這個物件可能會有這些問題:
1.實體變數會非常多,名稱有可能會重覆。
2.方法也會非常多,名稱有可能會重覆。
3.綜合1,2,可以得知在寫程式時,光要找名稱就要找很久了,且程式碼也難以管理。
在Programing in Objective-C 2.0書中,以一個Square class來作例子,來說明Composite。這個Square class不是之前做為Rectangle class的subclass,而是和Rectangle class 平級的 class:
這是Rectangle class宣告定義:
@interface Rectangle : NSObject {
int width;
int height;
}
@property int width, height;
-(int) area;//求長方型面積
-(int) perimeter;//求長方型週長
-(void)setWidth: (int)w andHeight:(int) h;//設定長與寛
-(id)initWithWidth:(int)w andHeight:(int)h;//初始化並設定長與寛
@end;
Rectangle 類別實作(@implementation)的部分這裡不贅述,現在是本文的重點Square類別:
//Square類別 composite Rectangle類別
@interface Square : NSObject {
Rectangle *rect;
}
-(void)setSide:(int)s;//設定正方型邊長
-(int)side;//求正方型邊長
-(int)area;//求正方型面積
-(int)perimeter;//求正型週長
-(id)initWithSide:(int)s;//初始化對設定正方型邊長
@end
@implementation Square
-(void)setSide:(int)s{
[rect setWidth:s andHeight:s];
}
-(int)side{
return [rect width];
}
-(int)area{
return [rect area];
}
-(int)perimeter{
return [rect perimeter];
}
-(id)init{
self = [super init];
rect = [Rectangle alloc] init]
return self;
}
-(id)initWithSide:(int)s{
self = [super init];
rect = [Rectangle alloc] initWithWidth:s andHeight:s];
return self;
}
-(void)dealloc{
[rect release];
[super dealloc];
}
@end
注意到Square 類別的實作(implemented)時,都是使用其內含的Rectangle物件變數的方法來實作的。
這只是一個簡單的例子,但如果有某物件composite多個其他class的實體變數,其複雜度也和這個例子差不多。
@end
你可能會有興趣的文章:
限會員,要發表迴響,請先登入



