Object-C学习笔记四-----组合

本文通过一个汽车组成的实例,详细讲解了组合模式(Composition)在Objective-C中的应用。文章演示了如何创建基本组件(如轮胎和发动机),并通过这些组件构建更复杂的对象(如汽车)。此外,还介绍了如何使用继承来扩展基本组件的功能。

前面学习的时候知道继承是两个类之间的关系。

 一个项目可能会有很多部分组成。我们如何能更好的把他们组合在一起呢?我们认为在对象之间的才称之为composition.

就像一辆汽车由发动机和四个轮子组成。这样我们可以理解为一个汽车类由一个发动机类和轮子类组成。只有有了发动机和轮子才能有车子。所以我们要先创建轮子和发动机。

@interface Tire : NSObject
@end

@implementation Tire

-(NSString *) description
{
   return  (@"I am a tire.I last a while.");
}
@end

 

@interface Engine : NSObject
@end

@implementation Engine

-(NSString *) description
{
    return (@"I am a engine, Vrooom!");
}
@end

 

@interface Car : NSObject {
@private
    Engine *engine;
    Tire *tires[4];
}

-(void) setEngine:(Engine *) newEngine;
-(Engine *) Engine;

-(void) setTire:(Tire *) tire atindex:(int)index;
-(Tire *) tireatIndex :(int) index;


-(void) print;
@end//Car

 

@implementation Car

-(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) setEngine:(Engine *)newEngine
{
    engine = newEngine;
}

-(Engine *)Engine
{
    return engine;
}

-(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;
}

-(Tire *)tireatIndex:(int)index
{
    if(index<0||index>3)
    {
        NSLog(@"bad index %d in setTire:atindex:",index);
        exit(1);
    }
    return tires[index];
}

-(void) print
{
    NSLog(@"%@",engine);
    NSLog(@"%@", tires[0]);
     NSLog(@"%@", tires[1]);
     NSLog(@"%@", tires[2]);
     NSLog(@"%@", tires[3]);
}
@end

然后我们在main函数中实例化车类。

实例化车类 Car *car =[Car new]; 而c# 实例化是 Car car = new Car;

调用车类中的方法[car print];                  调用方法是 car.print();

轮子和发动机都有很多种,但是他们都是轮子和发动机,所以具体的轮子和发动机继承他们相应的类。

@interface AllWeatherRadial : Tire
@end


@implementation AllWeatherRadial

-(NSString *) description
{
    return (@"I am a tire for rain or shine");  
}
@end

 

@interface AllWeatherRadial : Tire
@end


@implementation AllWeatherRadial

-(NSString *) description
{
    return (@"I am a tire for rain or shine");  
}
@end

int main (int argc, const char * argv[])
{
    Car *car=[Car new];
    //Engine *engine =[Engine new];
     Engine *engine =[Slant6 new];
    [car setEngine:engine];
 
   
    for (int i=0 ; i<4; i++) {
        //Tire *tire=[Tire new];
        Tire *tire=[AllWeatherRadial new];
        [car setTire:tire atindex:i];
      
    }
    [car print];
    return 0;
}

1.set 和get方法就是用来读取数据来用的,常用在set方法的时候用set做为前缀,但是get方法时,不常用get方法做为前缀,因为在object-c里面get方法会认为当作参数传入的指针来返回数值。

2.init方法,中的if判断这么做是为了防止超类在初始化过程中返回的对象不同于原先创建的对象。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值