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?
- 56
- 1
- 8
-
You could use Observable as explained here: http://stackoverflow.com/questions/13744450/when-should-we-use-observer-and-observable – LLL Apr 10 '17 at 07:20
-
Make bidirectional relation insteed of unidirectional and use paren's record value – Antoniossss Apr 10 '17 at 07:25
2 Answers
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
- 2,162
- 12
- 28
There is no easy way to do exactly that. Here are your options:
Just don't. Remove
valfromSubRecordand refactor every piece of code that tries to accessSubRecord.valto find theMainRecordand accessMainRecord.valinstead.Stop using immediate field access (
subRecord.val) and use getters instead, (subRecord.getVal()) as the universal trend is in java. Then, get rid ofSubRecord.valand rewrite yourSubRecord.getVal()as follows: instead of{ return val; }make it find itsMainRecordand doreturn mainRecord.getVal().Use the observer pattern. Your
MainRecordobject would need to have a list of observers, to which yourSubRecordobjects are added, so wheneverMainRecord.valchanges, all the observers get notified, so they can update their ownval.
- 56,297
- 11
- 110
- 142