天天看点

Object-c基础知识(二)继承复合

(好像是在Swift公布之前)这是前一段时间在某本书上看到的 ,感觉讲解的很详细,在此自己也总结下,让自己有进一步的加深理解。

本程序主要简单的涉及到了继承(之前总结过)、复合、代码重构、文件依赖关系知识点(都涉及的很少,但是可以)

由于程序简单,所有的类都再一个文件中。而不是将接口和实现文件分开。

其实分开是很好管理的对于大的项目。

 *之前已经讲了继承了,是的关系           复合:可以是一个类中,定义另一个类作为实例变量,类的复合  有的关系

 *进一步分析了object-c中存取方法的使用。存取方法总是成对出现的,一个用来设置属性的值,另一个用来读取属性值。

 *有时程序的需要只有一个getter方法(用于只读属性,例如磁盘文件大小),或者只有一个setter方法(例如密码设置)

 * 在cocoa中setter 方法是根据更改属性的名字命名的,前缀加set  ; 而getter方法直接用属性名字,没有前缀get

 *在本程序中对于实现存取方法时,没有考虑内存管理问题和对象所有权问题

如果要拆分文件

*拆分文件,(源文件组织) 比如在程序中,可以创建一个用来存放用户界面类的群组,可以再创建一个用来存放数据处理类的群组

 *主要拆分接口和实现两个文件

 *要区分#improt <>  和 #import ""的区别  前者用于导入系统头文件,后者用于导入项目本地的头文件;

 *依赖关系:在这种依赖关系中,头文件或者源文件需要使用另一个头文件的信息。 文件导入过于混乱延迟编译时间,也会导致不必要的重复编译   @class    #import

import <Foundation/Foundation.h>

@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 .");
}
@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

@implementation Car

-(Engine *)engine{
    return engine;
}
-(void) setEngine:(Engine *) newEngine{
    engine = newEngine;
}

-(Tire *) tireAtIndex:(int)index{
    if (index < 0 || index >3) {
        NSLog(@"error index!");
        exit(1);
    }
    return tires[index];
}
-(void) setTire:(Tire *) tire atIndex: (int) index{
    if (index <0 || index >3) {
        NSLog(@"index error!");
        exit(1);
    }
    tires[index] = tire;
}
-(void)print{
    NSLog(@" %@ ",engine);
    NSLog(@" %@",tires[0]);
    NSLog(@" %@",tires[1]);
    NSLog(@" %@",tires[2]);
    NSLog(@" %@",tires[3]);
}
@end


@interface Slant : Engine
@end

@implementation Slant

-(NSString *)description{
    return @"i am a slant6!";
}
@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[])
{

    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        Car *car = [Car new] ;
        
        Engine *engine = [Engine new];
        [car setEngine:engine];
        
        for (int i =0; i<4; i++) {
            Tire *tire = [Tire new];
            [car setTire:tire atIndex:i];
        }
        
        [car print];
        
        Engine *slant = [Slant new];
        [car setEngine:slant];
        
        for (int i=0; i<4; i++) {
            Tire *alltire = [AllWeatherRadial new];
            [car setTire:alltire atIndex:i];
        }
     
        [car print];
    }
    return 0;
}
           

之前还有简单的程序没有写出来,本程序是在其基础上进行修改了。

重构的概念在这里有所体现。   改进了内部架构,但是并没有影响它的外部行为;具体的说,代码 移植和优化的方式就是重构。 进行重构时,会通过移植某些代码来改进程序的架构,但是代码的运行结果没有收到影响。

点击打开链接