Search code examples
oopmessage-passing

Message passing between objects - How to refer to the target object?


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?


Solution

  • 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