views:

529

answers:

5

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?

A: 

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.

scubabbl
Thanks! This would make sense if you had messages that many objects could respond to. I'm really more interested in the general case where two objects are fairly closely coupled and are talking to each other. The OOP-101 type stuff. :)
Sam Hoice
+3  A: 

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.

tdavies
Thanks! I've spent a little time looking at Spring, but not much. I will definitely take a deeper look.
Sam Hoice
+2  A: 

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

rob_g
A: 

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();
xanadont
A: 

I think that it highly depends on what the exact relation is between the two objects.

Rik