假如有以下實體類
實體類聲明(.h)
@interface ZDWCar : NSObject
@property (nonatomic, copy) NSString *brand;
@property (nonatomic, copy) NSString *country;
@property (nonatomic, strong) UIColor *color;
@property (nonatomic, assign) CGFloat price;
此處省略n多property...
通骋В可以有以下創(chuàng)建方法:
方法1:
ZDWCar *myCar = [[ZDWCar alloc] init];
myCar.brand = @"wzd";
myCar.country = @"China";
myCar.color = [UIColor redColor];
myCar.price = 111000;
其它property賦值...
這種方法的缺點是時間久了會記不住這個類到底有哪些property需要在創(chuàng)建時初始化,尤其是這個類是有他人提供時搂擦,如果沒有注釋將會變得十分痛苦??。
方法2:
類創(chuàng)建者在實體類中添加多個init方法哗脖,比如:
- (instancetype)initWithBrand:(NSString *)brand;
- (instancetype)initWithBrand:(NSString *)brand country:(NSString *)country;
- (instancetype)initWithBrand:(NSString *)brand country:(NSString *)country color:(UIColor *)color;
- (instancetype)initWithBrand:(NSString *)brand country:(NSString *)country color:(UIColor *)color price:(CGFloat)price;
...
這種創(chuàng)建方法清晰地告訴調用者到底有哪些property需要在創(chuàng)建時初始化瀑踢。但是,當類的提供者有一天告訴你他增加了一個屬性才避,init方法也變了橱夭。這時,你是不是想死桑逝?還有如果當需要初始化的property比較多時棘劣,一排排的init豈不是很壯觀???
當某實體類的屬性值很多時楞遏,特別是當類將來是要提供給其他人用時茬暇,可以使用生成器模式:
在聲明文件(.h)中添加
typedef void(^ZDWCarBulderBlock)(ZDWCarBuilder *builder);
+(instancetype)createWithBuilder:(ZDWCarBulderBlock)block;
在定義(.m)文件中添加
+(instancetype)createWithBuilder:(ZDWCarBulderBlock)block {
NSParameterAssert(block);
ZDWCarBuilder *builder = [[ZDWCarBuilder alloc] init];
block(builder);
return [builder build];
}
生成器類聲明(.h)
@interface ZDWCarBuilder : NSObject
@property (nonatomic, copy) NSString *brand;
@property (nonatomic, copy) NSString *country;
@property (nonatomic, strong) UIColor *color;
@property (nonatomic, assign) CGFloat price;
- (ZDWCar *)build;
生成器類定義(.m)
- (ZDWCar *)build {
//設置brand和country為必須初始化的屬性,不傳會整段垮掉,??
NSParameterAssert(self.brand);
NSParameterAssert(self.country);
ZDWCar *car = [[ZDWCar alloc] init];
car.brand = self.brand;
car.country = self.country;
car.color = self.color;
car.price = self.price;
return car;
}
調用方實例
ZDWCar *myCar = [ZDWCar createWithBuilder:^(ZDWCarBuilder *builder) {
builder.brand = @"wzd";
builder.country = @"China";
builder.color = [UIColor redColor];
builder.price = 111000;
}];