iOS设计模式(生成器模式)
2018-07-01 本文已影响0人
hfzhangzhang
生成器模式
设计模式的一种,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
实用场景
1 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
2 当构造过程必须允许被构造的对象有不同表示时。
指导者根据传入的参数,让生产者生产,返回产品。
OC
@interface DrawBuilder : NSObject
- (CGFloat)buildLabel; /**< 构建label */
- (CGFloat)buildButton; /**< 构建按钮 */
- (CGFloat)buildSizeView; /**< 构建蓝色的View */
- (DrawView *)loadView; /**< 构建结果 */
@end
- (CGFloat)buildLabel {
return 0;
}
- (CGFloat)buildButton {
return 0;
}
- (CGFloat)buildSizeView {
return 0;
}
- (DrawView *)loadView {
CGFloat drawWidth = 200;
CGFloat drawHeight = 300;
DrawView *drawView = [[DrawView alloc] initWithFrame:CGRectMake(0, 0, drawWidth, drawHeight)];
//
drawView.buildLabel = [self buildLabel];
drawView.buildButton = [self buildButton];
drawView.buildSizeView = [self buildSizeView];
return drawView;
}
@interface DrawSubBuilderOne : DrawBuilder
@end
@implementation DrawSubBuilderOne
- (CGFloat)buildLabel {
return 1;
}
- (CGFloat)buildButton {
return 1;
}
- (CGFloat)buildSizeView {
return 1;
}
@end
@interface DrawSubBuilderTwo: DrawBuilder
@end
@implementation DrawSubBuilderTwo
- (CGFloat)buildLabel {
return 10;
}
- (CGFloat)buildButton {
return 150;
}
- (CGFloat)buildSizeView {
return 100;
}
@end
@interface Director : NSObject
+ (DrawView *)creatView:(DrawBuilder *)builder;
@end
@implementation Director
+ (DrawView *)creatView:(DrawBuilder *)builder {
DrawView *drawView = [builder loadView];
return drawView;
}
@end
#########
DrawBuilder *builder = [[DrawSubBuilderTwo alloc] init];
// 组装
DrawView *drawView = [Director creatView:builder];
drawView.center = self.view.center;
[self.view addSubview:drawView];