作者係文中比較java同objective C 嘅 OO。Objective C 嘅pattern係比較嚴格,可以由當中學到一D OOP嘅good practise.
Objective C 好似係冇所謂嘅public, private 同 protected 嘅 object function,作者係文中提及點樣可以做到E幾個keyword嘅效果。由於Objective C 歷史較長,佢冇E D keyword唔係因為佢design得唔好,可能係調返轉,果D keyword係由Objective C 啟發出來。
同埋我地design一個class嘅時候,要注意到
- Interface 要簡單
- 唔好expose不必要嘅function
- 要包好個object,隐藏implementation嘅detail
文中提出一個例子。解釋obejct method要簡單。1
2
3
4
5
6
7@interface Sark : NSObject
- (instancetype)init;
- (instancetype)initWithName:(NSString *)name;
- (instancetype)initWithName:(NSString *)name sex:(NSString *)sex;
- (instancetype)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age;
- (instancetype)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age friends:(NSArray *)friends;
@end
其實E個係java一個叫telecope constructor嘅anti-pattern,只要轉用builder pattern就可以解決
文中指出,可以用class method 去取代一D不必要嘅instance method。簡單去諗,只要個class冇多過一個instance,咁其實可以直接用class method。但係有一個pattern 叫 singleton,都係一個class得一個instance,咁幾時用class,幾時用singleton?
參考
http://blog.sunnyxx.com/2014/04/13/objc_dig_interface/
http://www.captaindebug.com/2011/05/telescoping-constructor-antipattern.html#.V2_1hpN97Vo
https://kodelog.wordpress.com/tag/telescopic-constructor-pattern/