Copying listeners/observers in a copy constructor
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?
The answer is it depends on what you want to happen.
There are technically three things you can do:
- Copy nothing. Any observers will know nothing about the new object.
- 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.
- 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.
Don't copy. The listeners are not aware of the new object and are not expecting to receive messages related to it.