关于建造者模式的个人理解
建造者模式适用于一个复杂的对象,但是他有多种构建方式,而且每种构建方式都不简单,写在一起不方便维护.建造者模式可以帮助分离对象和它的构建,使得调用相同的一个方法可以创建不同的表示.
比如说 蛋糕 对象,使用者需要通过调用一个方法,只要传入不同的参数,就可以返回草莓蛋糕,黑森林蛋糕,芝士蛋糕(懒得写了)等.
举蛋糕的例子:
怎么做蛋糕
1 2 3 4 5 6 7 8 9 10 11 12
| - (void)viewDidLoad { [super viewDidLoad]; // 想要什么蛋糕就只要实例化这个蛋糕(下订单) CakeBulider *bulider = [[StraberryCakeBulider alloc] init]; // 然后让蛋糕店去做蛋糕 Cake *cake = [CakeStore createCake:bulider]; // 看看蛋糕长什么样子 NSLog(@"%@",cake.description); }
|
Cake.m 蛋糕实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @interface Cake : NSObject
@property (nonatomic, assign)NSInteger *self.scream; @property (nonatomic, copy)NSString *self.ingredients; @property (nonatomic, assign)NSInteger *self.bakeTime;
@end
@implementation Cake
- (NSString *)description{ return [NSString stringWithFormat:@"我是一个蛋糕:奶油分量%zd 配料%@ 烘焙时间是:%zd",self.scream,self.ingredients,self.bakeTime]; }
|
CakeStore.m 卖蛋糕的店铺
1 2 3 4 5
| + (Cake *)createCake:(CakeBulider *)bulider { Cake *cake = [bulider bakeCake]; return cake; }
|
CakeBulider.m 蛋糕自动烘焙机
1 2 3 4 5 6 7 8
| - (Cake *)bakeCake { Cake *cake = [[Cake alloc] init] cake.scream = self.scream cake.ingredients = self.ingredients cake.bakeTime = self.bakeTime retrn cake }
|
StrawberryCakeBulider.m 草莓蛋糕
1 2 3 4 5 6 7 8 9 10 11 12 13
| @interface StrawberryCakeBulider():Cake @end
- (instancetype)init { self = [super init]; if (self) { self.scream = 10; self.ingredients = @"strawberry"; self.bakeTime = 10; } return self; }
|
BlackForestCakeBulider.m 黑森林蛋糕
1 2 3 4 5 6 7 8 9 10 11 12 13
| @interface BlackForestCakeBulider():Cake @end
- (instancetype)init { self = [super init]; if(self){ self.scream = 11; self.ingredients = @"cholocate"; self.bakeTime = 5; } return self; }
|
(话说大半夜的写蛋糕真的好吗)
其实QCCloud那个项目说不定就会用到这个模式,所以在这里稍微复习一下,回忆之前的知识.
(明天再去复习别的即将会用到的设计模式)