Copy listeners / observers in copy constructor

I am programming a class that implements an observable pattern (not an interface), and I am thinking about whether the constructor should copy the listeners as well.

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

On the other hand, this suggests that listeners can handle such things.

Any thoughts? Are there any better methods?

+4
source share
4 answers

The answer depends on what you want to do .

Technically you can do three things:

  • Copy nothing. Any observers will not know anything about the new facility.
  • Let the new object add itself to the list of things that old observers observe. Existing observers will respond to the new facility, as will the old one.
  • Create new observers who are watching the new object, as the old ones made the old object. New observers will respond to changes in the new facility, like old ones made for the old facility.

Other posters are certainly right that 1) is likely to be the preferred option, if only because executing 2 or 3 in the copy constructor means that observers are always created / copied. Nothing allows you to add observers later, if necessary.

However, you can imagine cases where other options are correct. If you want the observer to respond to any instance of this class, regardless of how it is created, then 2) is correct. If your observer performs a specific task for the object and does not care about the rest of the system, then 3) there may be a way.

It is often better to think about how your system works, rather than just following the rule. If this is not your code that you are modifying, contact the owner. And if you just don’t know what you want, select 1) and add observers later.

+3
source

Do not copy. Listeners are unaware of the new object and do not expect to receive messages related to it.

+5
source

My preference would be not to copy the listeners .

Listeners were registered on the original object, not on the copy - if you decided to use copy constructors as the basis for the prototype template, then you will get the same listeners who listened to almost all objects in the system.

However: as with all these types of problems, start with a minimum (i.e. don't copy), and then see how you do it. If you find that you are repeating the same bit of code immediately after building the object, every time you use this constructor (say, more than 3-4 times), a second review of this solution can be fruitful.

+1
source

Do not copy.

0
source

All Articles