I would like to have some guarantee that instances of some particular class Content
is only accessed by its "owner", and if another object wants the same Content
it needs to take a deep copy. Coming from C++ I would achieve that using a unique_ptr
, is there anything similar in Java?
Currently I am resolving this by just keeping the Content
private everywhere I keep one and paying attention to creating a new Content
(the constructor implements the deep copy mechanism) on a getContent
. But I have no means of enforcing possible other users of the Content
class to follow the same pattern, it's easy to forget. It would be nicer if it could take care of itself somehow, like not being copyable.
I realize that it goes somewhat against the spirit of the language, but in some cases I think it's justified. For example, if Content
represents some stream of data that is modified even by reading it. I thought, if not in the core language, maybe there is some @interface
for compile-time checking or a way of creating one?
Edit: The idea is that the owner can modify the object freely, before or after taking copies, and if someone takes a deep copy, they can modify theirs (not affecting the original), so making the Content
immutable is a bit too harsh (unless I'm misunderstanding what that implies).
There are a couple of common strategies here:
In this strategy, you'd have the owner have a private reference to the content, and if it's appropriate for it to give out copies of that content, to do so via a defensive copy:
class Owner {
private Content content;
// ...unnecessary detail omitted...
public Content getContent() {
return new Content(this.content);
}
}
The Cloneable
interface can sometimes be useful here.
The other common strategy is to use immutable objects (e.g., ensure that Content
, once instantiated, cannot be modified). Then you don't care who has a reference to the content, since they cannot change it.
No there isn't.
Once you have established a reference to an object, there's absolutely nothing you can do to stop someone form assigning another reference to that object via that established reference.
Java programmers get round this by making objects immutable (see java.lang.String
). Then you ought not give two hoots about who else is referring to a particular instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With