码迷,mamicode.com
首页 > 移动开发 > 详细

iOS设计模式 - 生成器

时间:2015-09-14 21:13:47      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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

 

分析

关系伦理图

技术分享 

 

iOS设计模式 - 生成器

标签:

原文地址:http://www.cnblogs.com/YouXianMing/p/4808120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!