I have a Load class and a Cargo class. An instance of Load contains an instance of Cargo.
class Load {
Cargo cargo
}
class Cargo {
String name
BigDecimal cost
}
Lets say that the name of an instance of Cargo is “rock” and the cost is “11.11”. Now I use this instance of Cargo to create an instance of Load. Now that the instance of Load has been created I don’t want it’s “cargo” to change. For instance, if I change the price of “rock” to “22.22” I don’t want the price of the “cargo” in my instance of Load to change. What is the optimal way to handle such a situation?
Well, if you can only have one Cargo per Load (as per your example), you’ll want to add a
costproperty to Load. Then you will need to copy over the cost at the time the objects are created. You might be able to do this via an overloaded method in the Load object, or just write your own method to add Cargo to Load.If you actually need multiple Cargoes per Load, then you’ll want an intermediate object to represent the connection. This object will store the price at the time they were associated. That might look like:
Of course, your object model will be a bit more complicated, because of the indirect relationship to Cargo.
Edit
Another way to handle the multiple-related situation is to duplicate the Cargo every time the cost is updated. This might be more efficient if you are expecting
costto be mostly static. I’d handle this by adding a field to “disable” items, like so:I believe you can simply clone the Cargo on update like this:
That’s just a guess, it probably is broken.