有的時候痒芝,對于一些相近的類功能都差不多,如果為此創(chuàng)建不同的類牵素,那實際調(diào)用接口的時候我們將要記住很多類才能正確調(diào)用吼野,但其實這時我么可以參照蘋果的設(shè)計思想(如NSNumber中 [NSNumber numberWithInt:1]; [NSNumber numberWithFloat:2.0f]等其實都是由NSNumber的內(nèi)部子類完成的,這其實就利用了類簇的設(shè)計思想)两波,我們可以利用這種設(shè)計思想統(tǒng)一暴露外部接口瞳步,在類中創(chuàng)建內(nèi)部類的方法實現(xiàn)具體的方法,調(diào)用的時候只要記住一個類腰奋,然后調(diào)用相應(yīng)的方法就行了单起。
首先,我們創(chuàng)建一個抽象的工程類劣坊,在其中創(chuàng)建一些私有的子類:LZHTransportFactory
#import <Foundation/Foundation.h>
typedef enum{
TransportCar,
TransportShip
}TransportName;
@interface LZHTransportFactory : NSObject
+(LZHTransportFactory*)factoryWithName:(TransportName)transoprname;
-(void)run;
-(int)shouldPay;
@end
#import "LZHTransportFactory.h"
@interface LZHCarFactory:LZHTransportFactory
@end
@implementation LZHCarFactory
-(void)run{
NSLog(@"carRun");
}
-(int)shouldPay{
NSLog(@"shouldPay100");
return 100;
}
@end
@interface LZHShipFacatory : LZHTransportFactory
@end
@implementation LZHShipFacatory
-(void)run{
NSLog(@"shipRun");
}
-(int)shouldPay{
NSLog(@"shouldPay 1000");
return 1000;
}
@end
@implementation LZHTransportFactory
+(LZHTransportFactory*)factoryWithName:(TransportName)transoprname{
switch (transoprname) {
case TransportCar:
return [LZHCarFactory new];
default:
return [LZHShipFacatory new];
}
}
-(void)run{
NSLog(@"putongrun");
}
-(int)shouldPay{
return 0;
}
@end
在ViewController 里面寫下一下代碼:
LZHTransportFactory * car = [LZHTransportFactory factoryWithName:(TransportCar)];
[car run];
LZHTransportFactory * ship = [LZHTransportFactory factoryWithName:(TransportShip)];
[ship run];
打印結(jié)果如下
2016-11-07 14:47:40.242 aaaa[14438:3810428] carRun
2016-11-07 14:47:40.242 aaaa[14438:3810428] shipRun
這樣統(tǒng)一使用LZHTransportFactory 作為抽象類的入口嘀倒,然后調(diào)用接口API,實際內(nèi)部有不同子類完成工作的方式就是類簇的設(shè)計模型了。