标签:
iOS设计模式 - 生成器
原理图
说明
1. 将构建复杂对象的过程拆分成一个一个的模块,通过统一的指导者来指导对象的构建过程称之为生成器模式
2. 生成器模式适合用于构建组合的对象
源码
https://github.com/YouXianMing/BuilderPattern
// // CarBuilder.h // BuilderPattern // // Created by YouXianMing on 15/9/14. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface CarBuilder : NSObject { NSMutableDictionary *_carInfo; } /** * 汽车信息 */ @property (nonatomic, strong, readonly) NSDictionary *car; /** * 建造轮子 */ - (void)buildWheel; /** * 建造引擎 */ - (void)buildEngine; /** * 构造外壳 */ - (void)buildShell; @end
// // CarBuilder.m // BuilderPattern // // Created by YouXianMing on 15/9/14. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "CarBuilder.h" @interface CarBuilder () @end @implementation CarBuilder - (instancetype)init { self = [super init]; if (self) { _carInfo = [[NSMutableDictionary alloc] init]; } return self; } - (void)buildWheel { _carInfo[@"wheel"] = @"normal_wheel"; } - (void)buildEngine { _carInfo[@"engine"] = @"normal_engine"; } - (void)buildShell { _carInfo[@"shell"] = @"normal_shell"; } @synthesize car = _car; - (NSDictionary *)car { return [[NSDictionary alloc] initWithDictionary:_carInfo]; } @end
// // BMWBuilder.h // BuilderPattern // // Created by YouXianMing on 15/9/14. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "CarBuilder.h" @interface BMWBuilder : CarBuilder @end
// // BMWBuilder.m // BuilderPattern // // Created by YouXianMing on 15/9/14. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "BMWBuilder.h" @implementation BMWBuilder - (void)buildWheel { _carInfo[@"wheel"] = @"BMO_wheel"; } - (void)buildEngine { _carInfo[@"engine"] = @"BMO_engine"; } - (void)buildShell { _carInfo[@"shell"] = @"BMO_shell"; } @end
// // ViewController.m // BuilderPattern // // Created by YouXianMing on 15/9/14. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "ViewController.h" #import "CarBuilder.h" #import "BMWBuilder.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CarBuilder *builder = [[CarBuilder alloc] init]; [builder buildEngine]; [builder buildShell]; [builder buildWheel]; NSLog(@"%@", builder.car); CarBuilder *bmwBuilder = [[BMWBuilder alloc] init]; [bmwBuilder buildEngine]; [bmwBuilder buildShell]; [bmwBuilder buildWheel]; NSLog(@"%@", bmwBuilder.car); } @end
分析
关系伦理图
标签:
原文地址:http://www.cnblogs.com/YouXianMing/p/4808120.html