(好像是在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;
}
之前還有簡單的程式沒有寫出來,本程式是在其基礎上進行修改了。
重構的概念在這裡有所展現。 改進了内部架構,但是并沒有影響它的外部行為;具體的說,代碼 移植和優化的方式就是重構。 進行重構時,會通過移植某些代碼來改程序式的架構,但是代碼的運作結果沒有收到影響。
點選打開連結