复合类 |
5.复合类
现实中,复杂的对象都是由较小和较为简单的对象构成;
由简单对象创建复杂对象的过程称作合成。
合成通常使用在有has-a关系的对象;
通常的基本数据类型可以满足构造简单和小的对象。
为了从小的对象创建复杂的对象,C++提供了复合类-将小的类作为复合类的成员变量
复合类的好处:
A)每个单独的类可以保持相对简单和直观,负责其自己的任务;
B)每个对象可以自包含,更易重用;
C)复合类使用简单的类完成复杂的工作,只需注重子类之间的数据流程。
XYPoint类 |
XYPoint.h文件
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject{
int x;
int y;
}
@property (nonatomic)int x,y;
-(void)setX:(int)_x andY:(int)_y;
@end
XYPoint.m文件
#import "XYPoint.h"
@implementation XYPoint
@synthesize x,y;
-(void)setX:(int)_x andY:(int)_y{
x=_x;
y=_y;
}
@end
Circle 类 |
Circle.h文件
#import <Foundation/Foundation.h>
@class XYPoint;
@interface Circle : NSObject{
int radius;
XYPoint* origin;
}
@property int radius;
-(XYPoint* )origin;
-(void)setOrigin:(XYPoint*)pt;
-(double)area;
-(double) perimeter;
-(void)print;
@end
Circle.m文件
#import "Circle.h"
@implementation Circle
@synthesize radius;
-(void)setOrigin:(XYPoint *)pt{
origin=pt;
}
-(double)area{
return (radius*radius);
}
-(double)perimeter{
return 2*3.14*radius;
}
-(XYPoint*) origin{
return origin;
}
-(void)print{
NSLog(@"Area =%f, Perimeter = %f",[self area],[self perimeter]);
}
@end
main函数 |
main.h文件
#import <Foundation/Foundation.h>
#import "XYPoint.h"
#import "Circle.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Hello, World!");
XYPoint* point=[[XYPoint alloc] init];
[point setX:2 andY:2];
Circle* c=[[Circle alloc] init];
c.radius=100;
[c setOrigin:point];
c.origin=point;
NSLog(@"origin at %d ,%d",c.origin.x,c.origin.y);
NSLog(@"radius = %d",c.radius);
NSLog(@"Area =%f, Perimeter = %f",[c area],[c perimeter]);
[c print];
[c release];
[point release];
}
return 0;
}