Ann Mathews
Ann Mathews

Reputation: 56

How can we make a value on one object reflect in a value in another object of a different type?

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

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 62054

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.

Upvotes: 0

Nestor Sokil
Nestor Sokil

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

Related Questions