在使用UITableView & UICollectionView的同时,我正在研究如何编写模块化、干净的代码,我发现了Objc.io关于编写轻量级ViewControllers的很好的博客。在遵循作者给出的实践时,我想到了一个关于Same Cell type and Multiple Model Object的段落,没有详细介绍,只是描述性的。我只想问,有没有人建议我们如何以更好、更模块化的方式来实现这一点?这段话是这样写的,
In cases where we have multiple model objects that can be presented using the same cell type, we can even go one step further to gain reusability of the cell. First, we define a protocol on the cell to which an object must conform in order to be displayed by this cell type. Then we simply change the configure method in the cell category to accept any object conforming to this protocol. These simple steps decouple the cell from any specific model object and make it applicable to different data types.
有人能解释一下这是什么意思吗?我知道这是离题的,但它可能会帮助一些人写更好的代码。
发布于 2016-06-16 18:34:32
这类似于引入ViewModel或ViewAdapter。一个简单的例子是单元格显示任何项目的描述。比方说,如果你给单元一个用户,它会显示他/她的全名。如果你发送邮件,它会显示主题。关键是,计算单元并不关心给它的确切内容(用户或邮件)。它只需要每个项目的描述,所以它需要从不同类型的的每个单独的模型中提取描述字符串的。那是ViewModel。
而不是: Cell => User或Cell =>新闻。用法: Cell => ViewModel =>用户或Cell => ViewModel =>新闻。代码示例:
class ViewModel {
private Object _item;
public ViewModel(Object item) {
_item = item;
}
public String getDescription() {
if (_item instanceof User) {
return ((User)_item).getFullName();
} else if (_item instanceof Mail) {
return ((Mail)_item).getSubject();
}
return "";
}
}https://stackoverflow.com/questions/37854600
复制相似问题