概括
類簇是一種設計模式(抽象工廠模式),它管理了一組隱藏在公共接口下的私有類。
詳解
簡單來說,我們調(diào)用的是父類抽象類,在抽象類里面會有諾干個私有子類,這些子類對于調(diào)用者來說是不公開的,然后會根據(jù)參數(shù)自動去實例化對應的子類。
下面看一個示例
NSMutableArray *array = [NSMutableArray new];
NSNumber *aInt = [NSNumber numberWithInt:1];
NSNumber *aBool = [NSNumber numberWithBool:YES];
NSString *aStr = @"xx";
在程序中設置一個斷點,可以看到對應變量的類型,這幾個變量的實際類型就是我們聲明對象的私有子類

子類類型
應用
在應用程序中,有時候需要做多條件的判斷,更有可能在項目的后期會增加更多的判斷,這個時候我們就可以考慮使用類簇
1 定義一個抽象類和兩個子類
@interface ClusterTest : NSObject
@end
@interface ClusterTestNew : ClusterTest
@end
@interface ClusterTestOld : ClusterTest
@end
2 把邏輯判斷放到抽象類里面
@implementation ClusterTest
+ (instancetype)alloc
{
if ([self class] == [ClusterTest class]) {
//為了避免重復調(diào)用
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
return [ClusterTestNew alloc];
} else {
return [ClusterTestOld alloc];
}
}
return [super alloc];
}
@end
@implementation ClusterTestNew
@end
@implementation ClusterTestOld
@end
3 使用
ClusterTest *test = [[ClusterTest alloc] init];
這樣如果系統(tǒng)版本是10及以上,則test是ClusterTestNew,否則為ClusterTestOld對象
4 總結(jié)
這樣有個好處就是在調(diào)用的地方顯得很簡潔,就算以后增加了判斷條件,也不會有任何的影響