ios Objective-C 5.0 复合
2018-07-18 本文已影响21人
Lost_Robot
复合和继承一样是建立两个类之间的关系的一种方式。
编程中的复合就像音乐中的作曲,将多个组件组合在一起,配合使用,从而得到完整的作品。
基本类型int、float、enum、struct这些基本类型只能是对象的一部分,只有对象间的组合才能叫做复合。
如:一辆汽车有一个发动机和4个轮子组成
@inteface <Foundation/Foundation.h>
@interface Tire:NSObject
- (NSString *) description
@end //Tire 类申明
@implementation Tire
- (NSString *) description{
return (@"I am a tire. I last a while.");
}
@end
//------------------------------Engine-----------------------
@interface Engine:NSObject
- (NSString *) description
@end //Engine类申明
@implementation Engine
- (NSString *) description{
return (@"I am a Engine.");
}
@end
- 在Cocoa中get有着特殊的含义,所以我们在申明属性的get和set方法时,建议最好不要使用get命名,这样会让开发者混淆,该方法的作用。
//------------------------------Car-----------------------
@interface Car:NSObject
{
Engine *engine;
Tire *tire[4];
}
-(void) setEngine:(Engine *) newEngine;
-(Engine *) engine;
-(Tire *) tireAtIndex:(int) index;
-(void) setTire:(Tire *) tire atIndex:(int) index;
-(void) print;
-(NSString *) description;
@end //Car类申明
@implementation Car
- (NSString *) description{
return (@"I am a Engine.");
}
-(Engine *) engine
{
return (engine);
}
-(void) setEngine:(Engine *) newEngine
{
engine = newEngine;
}
-(void) setTire:(Tire *) tire atIndex:(int) index
{
if(index <0 || index >3){
NSLog(@"bad index (%d) in setTire:atIndex: ",index);
exit(1);
}
tire[index] = tire;
} //setTire:atIndex;
-(Tire *) tireAtIndex: (int ) Index{
if(index <0 || index >3){
NSLog(@"bad index (%d) in setTire:atIndex: ",index);
exit(1);
}
return (tire[index]);
} //TireAtIndex;
@end
- 此处的代码使用的是防御式编程思想,防御式编程能够在开发的早期发现错误,比如数组的越界问题。
- 在Object-C中所有对象间的交互都是通过指针实现的,所以get方法返回的都是指针。
//------- Engine 的使用 -----------
Car *car = [Car new];
Engine *engine = [Engine new];
[car setEngine:engine];
NSLog(@"the car's engine is %@",[car engine]);
//---------Tire 的使用---------------
Tire *tire = [Tire new];
[car setTire:tire atIndex:2];
NSLog(@"tire number two is %@",[car tireAtIndex:2]);
//or
for(int i =0 ; i <4 ; i++ ){
Tire *tire = [Tire new];
[car setTire: tire atIndex: i];
}
[car print];
return (0);
2.如何使用继承和复合的形式组装Car
//---- new brand Engine ----
@interface Slant6:Engine
@end
@implemention Slant6
-(NSString *) descrption{
return (@"I am a slant - 6. VROOOM !");
}
@end //Slant6
//---- new brand Tire ----
@interface AllWeatherRadial:Tire
@end
@implemention AllWeatherRadial:Tire
-(NSString *) descrption{
return (@"I am a tire for rain or shine .");
}
@end //AllWeatherRadial
//----- main ------
Car *car = [Car new];
for(int i = 0;i<4;i++){
Tire *tire = [AllWeatherRadia new];
[car setTire:tire atIndex:i]
}
Engine *engine = [Slant6 new];
[car setEngine:engine];
[car print];
return (0);