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:

  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.

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

Need Your Help

Create a date range in mysql

mysql datetime

Best way to create on the fly, date ranges, for use with report.

Is there a limit on the number of measures in Mondrian or more specifically Saiku?

mondrian saiku

I have a couple of different data sets for which I am attempting to automate cube generation for Saiku 2.6. For the data sets with a limited number of dimensions and measures, it works pretty well...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.