请客吃饭与模板模式
- 张三李四王五,都实现了请客吃饭的流程,但具体实现是不一样的方法,比如有的用QQ,有的用手机
- 联系朋友,预订酒店,点菜,虽然有差异,但本质上都是按照这三个流程进行,
模板模式特点
- 过程殊途同归
- 将共同行为/流程抽象成算法的骨架
- 利用OO的多态,让子类继承重写
Cocoa 框架中用到的模板模式(Override)
CustomCell
@interface CustomCell : UITableViewCell
- (void)setupCell;
- (void)buildSubView;
@end
----------------------------------------
@implementation CustomCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
[self setupCell];
[self buildSubView];
}
return self;
}
- (void)setupCell {
}
- (void)buildSubView {
}
@end
ModelCell
@interface ModelCell : CustomCell
@end
@implementation ModelCell
- (void)setupCell {
// setup cell.
}
- (void)buildSubView {
// build subView.
}
@end
游戏从开始到结束的各个阶段详解
- 各个阶段的分解
- 将分解出来的阶段模板化
Game
@interface Game : NSObject
- (void)initGame;
- (void)pause;
- (void)save;
- (void)exitGame;
- (void)startPlay;
@end
@implementation Game
- (void)initGame {
}
- (void)pause {
}
- (void)save {
}
- (void)exitGame {
}
- (void)startPlay {
}
@end
Chess
@interface Chess : Game
@end
@implementation Chess
- (void)initGame {
NSLog(@"init chess game.");
}
- (void)pause {
NSLog(@"pasue chess game.");
}
- (void)save {
NSLog(@"save chess game.");
}
- (void)exitGame {
NSLog(@"exit chess game.");
}
- (void)startPlay {
NSLog(@"play chess game.");
}
@end
Football
@interface Football : Game
@end
@implementation Football
- (void)initGame {
NSLog(@"init football game.");
}
- (void)pause {
NSLog(@"pasue football game.");
}
- (void)save {
NSLog(@"save football game.");
}
- (void)exitGame {
NSLog(@"exit football game.");
}
- (void)startPlay {
NSLog(@"play football game.");
}
@end