复合: 对象间的组合(类中中包括类)
composition在音乐中翻译为作曲:将多个组件组合在一起,配合使用,从而得到完整的作品。在OC中,复合是通过包含作为实例变量的对象指针实现的。
@interface Car : NSObject
{
Engine *engine;
Tire *tires[4];
}
* (void)print;
@end //Car
自定义NSLog()
NSLog()
使用%@
格式说明符表示输出对象,也就是NSLog()
会给这个对象发送了description消息,然后对象的description方法生成一个NSString
并将其返回。**在类中提供description方法就可以自定义NSLog()
如何输出对象。
@interface Tire : NSObject
@end //Tire 轮胎
@implementation Tire
- (NSString *)description {
return (@"I am a tire.");
}
@end
int main(int argc, const char * argv[]) {
Tire *tire = [Tire new];
NSLog(@"%@", tire); // 输出 "I am a tire."
return 0;
}
存取方法
- 存取(accessor) 方法是用来读取或改变某个对象属性的方法。分为 getter方法 和 setter方法。
- 应该尽量使用对象提供的存取方法,不要直接改变对象里面的值。
存取方法总是成对出现的。
命名方式:setter方法在要更改属性的加上前缀set;getter方法直接是属性名称。
@interface Car : NSObject
{
Engine *engine;
Tire *tires[4];
}
- (Engine *) engine;
- (void) setEngine: (Engine *) newEngine;
- (Tire *) tireAtIndex: (int) index;
- (void) setTire: (Tire *) tire atIndex: (int) index;
- (void)print;
@end //Car
- 在OC中所有对象间的交互都是通过指针实现的。
复合还是继承
继承的关系:“Is a”(是一个)。如三角形是一个形状,Slant6是一个发动机……
复合的关系:“has a”(有一个)。如形状有个填充颜色,汽车有个发动机和四个轮胎……
详细代码
#import <Foundation/Foundation.h>
@interface Tire : NSObject
@end //Tire 轮胎
@implementation Tire
- (NSString *)description {
return (@"I am a tire.");
}
@end
@interface Engine : NSObject
@end //Engine
@implementation Engine
- (NSString *)description {
return (@"I am a Engine.");
} //description
@end
@interface Slant6 : Engine
@end //slant-6型号的发动机
@implementation Slant6
- (NSString *)description {
return (@"I am a slant-6型号的发动机.VROOM!");
}
@end
@interface AllWeatherRadial : Tire
@end // 新型轮胎
@implementation AllWeatherRadial
-(NSString *)description
{
return (@"I am a tire for rain or shine.");
}
@end
@interface Car : NSObject
{
Engine *engine;
Tire *tires[4];
}
- (Engine *) engine;
- (void) setEngine: (Engine *) newEngine;
- (Tire *) tireAtIndex: (int) index;
- (void) setTire: (Tire *) tire atIndex: (int) index;
- (void)print;
@end //Car
@implementation Car
- (Engine *) engine
{
return (engine);
} //engine
- (void) setEngine:(Engine *)newEngine
{
engine = newEngine;
} //setEngine
- (void) setTire:(Tire *)tire atIndex:(int)index
{
if (index<0 || index>3) {
NSLog(@"bad index (%d) in setTire:atIndex", index);
exit(1);
}
tires[index] = tire;
} // setTire
- (Tire *) tireAtIndex:(int)index
{
if (index<0 || index>3) {
NSLog(@"bad index (%d) in setTire:atIndex", index);
exit(1);
}
return tires[index];
} // tireAtIndex
- (id)init
{
if (self = [super init]) { //?
engine = [Engine new];
tires[0] = [Tire new];
tires[1] = [Tire new];
tires[2] = [Tire new];
tires[3] = [Tire new];
}
return (self);
}
- (void)print
{
NSLog(@"%@", engine);
NSLog(@"%@", tires[0]);
NSLog(@"%@", tires[1]);
NSLog(@"%@", tires[2]);
NSLog(@"%@", tires[3]);
}
@end
int main(int argc, const char * argv[]) {
Car *car = [Car new];
Engine *engine = [Slant6 new];
[car setEngine:engine];
for (int i=0; i<4; i++) {
Tire *tire = [AllWeatherRadial new];
[car setTire:tire atIndex:i];
}
[car print];
return 0;
}