将接口传递给对象,还是在 Cocoa 中使用委托?
我遇到的情况是,在基于文档的应用程序中有几层嵌套对象,需要了解有关特定模型的信息。
具体来说,我有一个 NSTextView、NSLayoutManager 和 NSTypesetter,它们都需要了解有关我的文档模型的某些属性才能正确呈现它。
目前,我已经对每个类进行了子类化,并为它们提供了一个引用我的模型的属性。该引用从我的文档控制器向下传递到子类 NSLayoutManager,然后传递到子类 NSTypesetter:
@implementation MyLayoutManager : NSLayoutManager {
@private
MyModel *model;
}
@property (retain) MyModel *model;
-(id)initWithModel:(MyModel *)model;
@end
@implementation MyTypesetter : NSATSTypesetter {
@private
MyModel *model;
}
@property (retain) MyModel *model;
-(id)initWithModel:(MyModel *)model;
@end
模型从 Controller->MyLayoutManager->MyTypesetter 传递。这似乎有点多余,也许耦合得太紧密了。
委托模式会更好吗?如果是这样,最好的设置方法是什么? Typesetter 没有委托,但 LayoutManager 已经有一个。应该向 Typesetter 添加委托,然后覆盖 LayoutManager 上的委托吗?或者坚持传递我的模型的界面是否更好?
任何见解将不胜感激。谢谢。
I have a situation where I have several layers of nested objects in a document-based application that need to know information about a certain model.
Specifically, I have an NSTextView, NSLayoutManager, and NSTypesetter, each of which need to know certain properties about my document model in order to correctly render it.
Currently, I have subclassed each of the classes, and given them a property that has a reference to my model. The reference is passed down from my document controller, to the subclassed NSLayoutManager, and then handed off to the subclassed NSTypesetter:
@implementation MyLayoutManager : NSLayoutManager {
@private
MyModel *model;
}
@property (retain) MyModel *model;
-(id)initWithModel:(MyModel *)model;
@end
@implementation MyTypesetter : NSATSTypesetter {
@private
MyModel *model;
}
@property (retain) MyModel *model;
-(id)initWithModel:(MyModel *)model;
@end
The model is passed from Controller->MyLayoutManager->MyTypesetter. This seems a little redundant a perhaps too tightly coupled.
Would the delegate pattern be better? If so, what is the best way to set that up? Typesetter has no delegate, but LayoutManager already has one. Should add a delegate to Typesetter, then override the delegate on LayoutManager? Or is it better to just stick with passing down my model's interface?
Any insight would be appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,最好将与模型的通信专门隔离给控制器,然后控制器将任务(根据需要提供相关信息)委托给其他涉及的对象。
虽然更加面向对象并且正确,但它并不总是最漂亮的。然而,它通常是最容易维护的。
Generally it's a good idea to isolate communication with the model exclusively to the controller, which then delegates out tasks (providing relevant information as necessary) to other objects involved.
While more OO and correct, it's not always the prettiest. It is generally the easiest to maintain however.