Java 最终不可变的不可变对象的设计模式
我想构造一个对象,将其作为不可变对象传递给应用程序的其余部分。然而,这里的问题是,有些字段在对象构造时直接可用,而有些字段需要来自RPC调用的响应。RPC调用需要一些时间才能返回,我不想在此期间阻止调用方,因为我希望调用方使用在对象构造期间传入的字段。我有一个设计的想法,但想知道是否有一个标准的模式 下面的例子说明了我在寻找什么Java 最终不可变的不可变对象的设计模式,java,design-patterns,Java,Design Patterns,我想构造一个对象,将其作为不可变对象传递给应用程序的其余部分。然而,这里的问题是,有些字段在对象构造时直接可用,而有些字段需要来自RPC调用的响应。RPC调用需要一些时间才能返回,我不想在此期间阻止调用方,因为我希望调用方使用在对象构造期间传入的字段。我有一个设计的想法,但想知道是否有一个标准的模式 下面的例子说明了我在寻找什么 public class Player { private int name; // Available at construction time priva
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;
}
}
<>这个例子不是线程安全的,考虑它会被处理。为了让感兴趣的调用者知道profileUrl何时可用,我将公开一个注册可调用项的方法,当profileUrl可用时将通知该方法
我认为,如果我再添加几个类似于profileUrl的字段,这种方法将无法很好地工作,而profileUrl最终将可用。我想知道解决这个问题的方法
如果我确保所有与profileUrl类似的字段同时可用(即,它们是使用单个方法设置的),这会简化吗?是否符合您的需要
代码段:
public class Player {
private int name; // Available at construction time
private int age; // Available at construction time
private String profileUrl = null; // Need to get this from an RPC call
Player(int name, int age) {
this.name = name;
this.age = age;
}
// usual getter methods
public String getProfileUrl() {
if (profileUrl == null) {
profileUrl = Remote.getProfileUrl();
}
return profileUrl;
}
}
您可以将RPC移动到访问器方法,在本例中为getProfileUrl
。
只有第一个调用实际上会阻止等待远程过程完成
对于需要这种大量初始化的字段,其他访问器方法看起来也一样
如果您可以以这种方式使用
Player
class,并且能够缓存profileUrl
以备将来调用,那么您就可以解决问题并实现此模式的目标。为什么不使用接口公开您希望外部代码使用的方法,而不公开进行更改的方法呢?当然,这将确保它不受外部世界的影响。在处理最终可用字段时,您如何看待问题的另一部分:hasField()、getField()&在字段可用时通知。我可以将所有这些字段合并到一个内部类中,并在单个调用中设置它们,并在设置时通知世界。但是有没有更好的方法呢?像Builder模式这样的东西对你有用吗?我相信如果我在创建对象之前有了所有的字段,Builder模式会很有用。在我的例子中,我在实例化对象时有几个字段,稍后将添加其他字段。除非你有不同的想法,否则我看不到一个简单的方法来应用它。你有静态访问RPC的权限吗?如果你这样做了,那么这个方法已经有了答案。实际上,我在一个企业规模的电子商务平台应用程序中遇到了这种情况,我通过在应用程序初始化时缓存大部分/部分大型数据来解决这种情况。如果你愿意,我可以分享代码……这是一个很好的答案。但你不认为OP可以通过这种方式访问RPC吗?