具有不同类型对象的复合图案
我想使用复合模式将一个对象收到的调用转发给其他对象。
目前,接收端的对象都是相同的抽象类型,但问题是它们根据具体类型选择性地接受不同类型的对象作为参数(想想不同的模型)。
据我所知,有两种解决方案,但都不是令人满意:
- 使用instanceof来检测输入端的类类型对象。这通常被认为是一种不好的做法。
- 创建与输入类型一样多的
列表
。这就带来了一个问题:必须添加一个List
来容纳新的输入类型,并且必须依次显式地处理每个List
。
我一直在考虑接口方面的问题,但到目前为止还没有提出一个可行的想法。这个设计问题的解决方案是什么?复合是否合适?
PS:这是在mvc的上下文中。
I'd like to use the Composite pattern for forwarding calls received by one object to others.
At present, objects on the receiving end are all of the same Abstract
type but the snag is that they selectively accept different types of objet as parameters according to their concrete type (think different models).
As far as I can see, there are two solutions but neither is satisfactory:
- Use instanceof to detect the class type objects on the input side. This is often said to be a bad practise.
- Make as many
Lists
as there are input types. This brings the problem that aList
has to be added to accomodate a new input type and eachList
has to be explicitely processed in turn.
I've been thinking in terms of interfaces but have not come up with a feasible idea as of yet. What would be a solution to this design issue? Is a composite appropriate at all?
P.S: This is in the context of an mvc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
复合模式允许您将对象集合视为叶对象。
我想说你可以做这样的事情:
这就是复合对我的意义。你是对的 - 如果你必须使用
instanceof
你就错了。Composite pattern allows you to treat a collection of objects the same as a leaf object.
I'd say that you could do something like this:
That's what Composite means to me. You're right - if you have to use
instanceof
you've done it wrong.我在 Java Practises 的 StocksMonitor 应用程序中发现了以下方法。这是 mvc 上下文中主视图的更新方法:
引用是不同模型的实例,用于有选择地更新相应的视图。这种方法尊重复合模式,并允许根据参数实例进行具体处理。当然,这仅依赖于运行时使用的模型的一个实例。
I've found the following approach in the StocksMonitor application at Java Practises. This is the update method of the Main view in an mvc context:
The references are instances of different models which are used to selectively update corresponding views. This approach respects the composite pattern and allows case-by-case processing according to the parameter instance. Of course, this relies on only one instance of a model being used at runtime.