I want to construct an object which I want to pass on to the rest of the application as an immutable object. However problem here is that some fields are directly available at object construction time whereas some require a response from an RPC call. RPC call takes some time to return and I do not want to block the callers during this time because I would like callers to use the fields which are passed in during the object construction time. I have a design in mind but wanted to know if there is a standard pattern.
Following example illustrates what I am looking for.
public class Player {
private int name; // Available at construction time
private int age; // Available at construction time
private String profileUrl; // Need to get this from an RPC call
// useful for checking whether we have profileUrl
private boolean profileUrlAvailable = false;
Player(int name, int age) {
this.name = name;
this.age = age;
}
// usual getter methods
// Package protected for immutability
void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
this.profileUrlAvailable = true;
}
public boolean hasProfileUrl() {
return profileUrlAvailable;
}
// throws if profile url is not yet available.
public String getProfileUrl() {
if (!profileUrlAvailable) {
throw new IllegalStateException("Profile url not available");
}
return profileUrl;
}
}
This example is not threadsafe, consider that it will be taken care of. To be able to let interested callers know when the profile url is available, I will expose a method to register callables which will be notified when the profileUrl is available.
I think this approach does not work well if I add few more fields similar to profileUrl which will eventually be available. I wanted suggestions on the ways to solve this.
Does it simplify if I make sure that all fields similar to profileUrl are made available at the same time (ie., they are set using a single method) ?
Aucun commentaire:
Enregistrer un commentaire