iOS设计模式之策略(strategy)模式

1、定义

定义一系列算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

如上UML类图,context类可以通过他持有的Strategy对象来创建不同的ConcreteStrategy对象,从而调用不同的algorithmInterface方法。


2、使用场景

在大量使用if-else或switch-case条件的业务场景下可以使用策略模式。

3、示例

比如今日头条新闻列表根据不同的新闻类型创建不同的cell就可以采用策略模式。如下代码所示

#define kClassKey @"kClassKey"

#define kModelKey @"kModelKey"

#define kReuseKey @"kReuseKey"

#define CellAID @"cellA"

#define CellBID @"cellB"

@interface PCCarOrderDetailViewController ()

@property (nonatomic,strong) NSMutableArray *dataSource;

@end

- (void)viewDidLoad

{

[super viewDidLoad];

[self registerTableViewCell]; //注册CellA和CellB

[self createDataSourceAndReloadData]; //构建数据源

}

- (void)registerTableViewCell

{

//注册cell

[self registerTableViewCellNibWithClass:[PCCellA class] reuseId:CellAID];

[self registerTableViewCellNibWithClass:[PCCellB class] reuseId:CellBID];

}

- (void)registerTableViewCellNibWithClass:(Class)cls reuseId:(NSString *)reuseId

{

if (!cls || !reuseId)

{

return;

}

[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass(cls) bundle:nil] forCellReuseIdentifier:reuseId];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

//通过策略模式避免了大量的if-else-if-else判断

NSDictionary* dic = self.dataSource[indexPath.row];

PCBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:dic[kReuseKey] forIndexPath:indexPath];

if ([cell respondsToSelector:@selector(initWithModel:)])

{

[cell initWithModel:dic[kModelKey]];

}

return cell;

}

- (void)createDataSourceAndReloadData

{

self.dataSource = [NSMutableArray array];

//订单状态

[self.dataSource addObject:[NSDictionary dictionaryWithObjectsAndKeys:[PCCellA class], kClassKey, [[PCModel alloc] init], kModelKey, CellAID, kReuseKey, nil]];

[self.dataSource addObject:[NSDictionary dictionaryWithObjectsAndKeys:[PCCellB class], kClassKey, [PCModel alloc] init], kModelKey, CellBID, kReuseKey, nil]];

[self.tableView reloadData];

}

@interface PCBaseCell : UITableViewCell

//子类可重写该类方法

- (void)initWithModel:(id)model;

@end

@interface PCCellA : PCBaseCell

- (void)initWithModel:(id)model; //重写该方法

@end

@interface PCCellB : PCBaseCell

- (void)initWithModel:(id)model; //重写该方法

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容