Reputation: 56
I have two classes SubRecord
and MainRecord
, which each have their individual fields. Neither of these is a subclass of the other. Multiple SubRecord
objects correspond to one MainRecord
object, as distinguished by field id
in both. There is a field val
in SubRecord
that corresponds to value val
in MainRecord
which is of type double
. How can I make it such that on updating val
in MainRecord
, all the corresponding objects of type SubRecord
simultaneously update their fields val
to the same value as well?
Upvotes: 0
Views: 56
Reputation: 62054
There is no easy way to do exactly that. Here are your options:
Just don't. Remove val
from SubRecord
and refactor every piece of code that tries to access SubRecord.val
to find the MainRecord
and access MainRecord.val
instead.
Stop using immediate field access (subRecord.val
) and use getters instead, (subRecord.getVal()
) as the universal trend is in java. Then, get rid of SubRecord.val
and rewrite your SubRecord.getVal()
as follows: instead of { return val; }
make it find its MainRecord
and do return mainRecord.getVal()
.
Use the observer pattern. Your MainRecord
object would need to have a list of observers, to which your SubRecord
objects are added, so whenever MainRecord.val
changes, all the observers get notified, so they can update their own val
.
Upvotes: 0
Reputation: 2272
I suppose your MainRecord
has a list of its subrecords. According to the common and obvious Java Bean pattern, the access to val
should be provided via a setter. So you can just modify the internals of you setVal
method like this:
public class MainRecord {
private double val;
private List<SubRecord> subs;
// ...
public void setVal(double newVal) {
this.val = newVal;
for(SubRecord entry : subs)
entry.setVal(newVal);
}
}
This is a very simple variation of an Observer pattern. See more here: https://en.wikipedia.org/wiki/Observer_pattern
Upvotes: 1