对象之间的消息传递——如何引用目标对象?
面向对象环境中最基本的任务是在对象上执行方法。 为此,您必须拥有对调用该方法的对象的引用。 建立此引用的正确方法是将对象作为参数传递给调用对象的构造函数(或初始化方法)吗?
如果对象 foo
调用对象 bar
,这样说(用伪代码)是否正确:
bar = new barClass()
foo = new fooClass(bar)
如果需要来回传递消息会发生什么? 您需要注册目标对象的方法吗?
foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
有解决这个问题的模式吗?
The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?
If object foo
calls into object bar
, is it correct to say (in pseudo-code):
bar = new barClass()
foo = new fooClass(bar)
What happens if you need to pass messages back and forth? Do you need a method for registering the target object?
foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
Is there a pattern that addresses this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
依赖注入框架,例如 Spring 和 Guice 通过使用代理来解决 Java 中的循环依赖关系,代理可以在第一次需要时解析消息的接收者。 然而,这不是普遍适用的 OO 模式。
Dependency injection frameworks like Spring and Guice provide a solution to cyclical dependencies in Java by using proxies which can resolve the receiver of a message the first time it is required. This isn't a generally applicable OO pattern, however.
一般来说,依赖注入是可行的方法。 如果您只是谈论两个对象进行通信,则将一个对象的实例作为参数传递给另一个对象,如第一个示例所示。 传入构造函数确保引用始终有效。 否则,您必须进行测试以确保已调用寄存器。 此外,您还需要确保多次调用寄存器不会产生不利影响。
如果您想要一个控制对象,其他对象可以向该对象注册事件,该怎么办? 那么就适合使用 Register 方法(可以添加到委托中)。
请参阅观察者模式
Generally dependency injection is the way to go. If you're just talking about two objects communicating then pass an instance of one in as a paramter to the other, as in your first example. Passing in the constructor ensure the reference is always valid. Otherwise you'd have to test to ensure register had been called. Also you'd need to make sure calling register more than once wouldn't have adverse effects.
What if you want a controlling object, to which other objects register for events. It would then be suitable to use a Register method ( which may add to a delegate).
See Observer Pattern
那么,根据消息传递的级别,您可以实现消息传递服务。 对象侦听消息,或在某些 MessageProvider 上注册为 MessageListener。
如果两个对象相互引用,最终会出现循环依赖关系,在大多数情况下我认为这很糟糕。
Well, depending on the level of messaging, you could implement a messaging service. Objects listen for messages, or register as a MessageListener on some MessageProvider.
You end up with cyclical dependencies if two objects have references to each other, which I would consider bad in most cases.
您的一种对象类型可能是另一种对象类型的工厂。 当 Foo 抛出一个新的 Bar 时,连接已经建立:
One of your object types could be a factory for the other. When Foo poops out a new Bar, the connection has already been made:
我认为这很大程度上取决于两个对象之间的确切关系。
I think that it highly depends on what the exact relation is between the two objects.