0

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?

Ann Mathews
  • 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 Answers2

1

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

Nestor Sokil
  • 2,162
  • 12
  • 28
0

There is no easy way to do exactly that. Here are your options:

  1. 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.

  2. 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().

  3. 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.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142