Message passing between objects - How to refer to the target object?
-
01-07-2019 - |
Question
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
OTHER TIPS
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.
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:
foo = new Foo();
bar = Foo.Poop();
function Foo::Poop()
{
bar = new Bar(this);
myChildren.Add(bar);
return bar;
}
bar.SayHiToParent();
foo.SayHiToChildren();
I think that it highly depends on what the exact relation is between the two objects.