Engine.h
Engine.h
#import <Foundation/Foundation.h>
@interface Engine : NSObject
@end
Engine.m
Engine.m
#import "Engine.h"
@implementation Engine
//重写description方法,这里只是重写description的属性的访问器,并不是重写description这个类方法
-(NSString *)description
{
return @"我是一个引擎,我在努力工作!";
}
@end
Tire.h
#import <Foundation/Foundation.h>
@interface Tire : NSObject
@end
Tire.m
#import "Tire.h"
@implementation Tire
-(NSString *)Tire
{
return @"我是一个轮胎,我诚恳的托起了整个车身";
}
@end
Car.h
Car.h
#import <Foundation/Foundation.h>
#import "Engine.h"
#import "Tire.h";
@interface Car : NSObject
{
@public
Engine *_engine; //引擎
Tire *_tire[4]; //四个轮胎(指针数组,数组中的每一个元素存储的都是一个地址,都指向Tire,即每个元素都是Tire的一个实例对象)
}
-(void)run;
-(void)setEngine:(Engine *)engine;
-(Engine *)engeine;
-(void)setTire:(Tire *)tire atIndex:(int)index;//轮胎带索引的setter方法
-(Tire *)tireAtIndex:(int)index;
@en
Car.m
#import "Car.h"
@implementation Car
-(void)run
{
NSLog(@"%@",_engine);
for (int i = 0; i<4; i++)
{
//NSLog(@"%@",_tire[i]); //没有调用校验
NSLog(@"%@",[self tireAtIndex:i]);//调用校验
}
}
-(void)setEngine:(Engine *)engine
{
_engine = engine;
}
-(Engine *)engeine
{
return _engine;
}
-(void)setTire:(Tire *)tire atIndex:(int)index
{
if (index<0 || index >3)
{
NSLog(@"设置轮胎不正确");
}
else
{
_tire[index] = tire;
}
}
-(Tire *)tireAtIndex:(int)index
{
if (index < 0 || index > 3)
{
NSLog(@"获取轮胎位置不正确");
return nil;
}
else
{
return _tire[index];
}
}
@end
mian.m
#import <Foundation/Foundation.h>
#import "Engine.h"
#import "Tire.h"
#import "Car.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
/*
复合
在oc中,就是一个类的成员变量是由其他的一些类组成,即一个类包含了好几个其他类
*/
Engine *engine = [Engine new];
Car *car = [Car new];
[car setEngine:engine];
for (int i = 0; i<4; i++)
{
Tire *tire = [Tire new];
[car setTire:tire atIndex:i];
}
[car run];
/*
继承是在对象之间建立'is-a'关系,但是不是任何情况下都适合使用的
复合,则是在对象之间建立了一个'has a'(有一个)的关系。如果能'X 有一个 Y',即可以使用复合
复合使用在将一些个体组合起来形成一个新的整体的情况下。
*/
}
return 0;
}