tags:

views:

120

answers:

4

I'm programming a class that implements the observable pattern (not the interface) and I'm thinking about whether or not the copy constructor should also copy the listeners.

On the one hand the copy constructor should create an instance that is as close as possible to the original instance so that it can be swapped out in the display context.

On the other hand this would assume the listeners can cope with that kind of thing.

Any thoughts? Are there any best practices?

A: 

Don't copy.

Tom Hawtin - tackline
+3  A: 

Don't copy. The listeners are not aware of the new object and are not expecting to receive messages related to it.

finnw
+1  A: 

My preference would be don't copy the listeners.

The listeners were registered on the original object, not the copy - if you decide to use copy constructors as a basis for a prototype pattern, then you'll end up with the same listeners listening to practically every object in the system.

However: as with all of these types of problems, start with a minimum (i.e. don't copy) and then see how you get on. If you find yourself repeating the same bit of code just after the construction of the object, every time you use that constructor (say more than 3-4 times), then revisiting this decision may be fruitful.

jamesh
+1  A: 

The answer is it depends on what you want to happen.

There are technically three things you can do:

  1. Copy nothing. Any observers will know nothing about the new object.
  2. Have the new object add itself to the list of things the old observers are observing. The existing observers will respond to the new object as they did the old.
  3. Create new observers that observe the new object, as the old ones did the old object. The new observers will respond to changes in the new object as the old ones did to the old object.

The other posters are certainly right that 1) is likely to be the preferred option, if only because doing 2 or 3 in the copy constructor means that the observers are always created/copied. Doing nothing allows for observers to be added later if necessary.

However it is possible to imagine cases where the other options are right. If you want an observer that responds to any instance of a given class, no matter how created, then 2) is right. If your observer does a specific task for the object, and doesn't care about the rest of the system then 3) might be the way.

It's often best to think about how your system works than just follow a rule. If this isn't your code that you are modifying, then ask the owner. And if you simply don't know what you want to happen, choose 1) and add the observers later.

DJClayworth