收藏品知道它所包含的收藏品 - 这有气味吗?
好吧,这可能是一个奇怪的问题,也许我正朝着错误的方向前进,但这是我的问题:
我有一个 SearchForm 对象,其中包含 Tag 对象的集合。当用户单击 Tag 对象时,它会突出显示自身并触发事件。 SearchForm 类侦听此事件并提交自身。 Tag 对象与 SearchForm 没有关系。
到目前为止,一切都很好。
现在,某些标签在单击时必须激活其他标签。每个标签都知道它必须激活哪些其他标签。但为了做到这一点,它必须了解搜索表单所持有的整个标签集合。
如果标签实例(=集合项)引用了所有其他标签(=集合)的完整列表,这会是“坏”吗?
当然,像这样的事情是可行的:
Tag is clicked -> SearchForm通知->检查单击的标签是否必须激活其他一些标签 -> SearchForm 本身激活所需的标签
。
但这似乎有点尴尬,是不是?
Allright, this might be a strange question and maybe I am heading the wrong direction, but here is my problem:
I have a SearchForm object which holds a collection of Tag objects. When a Tag object is clicked by the user, it highlights itself and triggers an event. The SearchForm class listens to this event and submits itself. The Tag object has no relation to the SearchForm.
So far, so good.
Now some Tags must activate other Tags when clicked. Each Tag knows what other Tags it must activate. But in order to do so it must KNOW about the whole collection of Tags held by the searchform.
Would it be "bad" if a Tag instance (= collection item) has a reference to the complete list of all other Tags (= collection)?
Of course some something like this would be doable:
Tag is clicked -> SearchForm is notified -> checks if the clicked tag must activate some others -> SearchForm activates the needed Tags itself
.
But this seems a bit akward, or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来这并没有什么问题。如果集合中的某个项目需要了解该集合中的其他项目,那么它也完全有理由了解整个集合。
大多数 GUI 框架以及您可能正在使用的 DOM 本身都具有了解其所在集合的集合项(在 DOM 中,在任何元素上,您可以调用
parentElement
来获取它的父级)。一般来说,如果对象“知道”的信息不超过它们所需的最小值,那么为了减少耦合,这是很好的。但如果一个对象确实需要了解某件事,那么给它一个引用并不是没有道理的。
It doesn't sound like there's anything wrong with that. If there's an item in a collection that needs to know about other items in the collection, it's perfectly reasonable for it to know about the collection as a whole as well.
Most GUI frameworks, and the DOM itself that presumably you're working with, have collection items that know about the collection they're in (in the DOM, on any element, you can call
parentElement
to get its parent).In general, it's good if objects don't "know" about more than the minimum they need, in order to reduce coupling. But if an object does need to know about something, giving it a reference to that isn't unreasonable.
集合中的某个项目知道其所在位置并不罕见……想想链表或树。如果您不希望标签知道整个列表,您可以仅添加对其相关标签的引用。
It's not uncommon for an item in a collection to know its whereabouts... think linked lists or trees. If you don't want the tag to know the whole list you might add a reference to its related tags only.
我认为这只是一个观察者设计模式。
我不懂javascript,但我想它应该是可行的。
无论如何,请避免对列表进行硬编码。
I think it's just an observer design pattern.
I don't know javascript but I guess it should be doable.
In any case avoid hard-coding your list.