如果對象是不可改變的,那麼你建立一個臨時的結構將在適當的順序(顯然,這並不適用於圓名單,除非你使用的設置最終場反射序列化支持)創建它們。
如果不是,請稍後在外部列表中記錄所需的操作,或者爲每個成員使用具有解析方法的接口: public interface IBar IBar resolve();
static IBar EMPTY = new IBar() {
public IBar resolve() {
throw new RuntimeException();
}
}
}
public interface IFoo {
IFoo resolve ();
...
}
public class Foo implements IFoo {
private IBar bar = IBar.EMPTY;
public Foo (IBar bar) { this.bar = bar; }
public Bar getBar() {
return bar.resolve();
}
public String getId() { ... }
public IFoo resolve() {
bar = bar.resolve();
return this;
}
}
public class Loader {
private HashMap<String,IFoo> fooRefs = new ...
private HashMap<String,IBar> barRefs = new ...
private IBar barRef (String id) {
IFoo foo = fooRefs.get(id);
if (foo==null) {
foo = new ForwardFooRef(id);
fooRefs.put(id,foo);
}
return foo;
}
private IFoo created (IFoo foo) {
IFoo extant = fooRefs.get(foo.getId());
if (extant != null)
if (extant instanceof ForwardFooRef)
((ForwardFooRef)extant).setReferent(foo);
else
throw new RuntimeException("more than one object with the same id ");
return foo;
}
public void load() {
create each object
register it using created
if a ref is found, use the maps to look it up
if the ref is in teh map, use it
if ref is forward, it's created with a temp
walk object tree resolving anything
您的示例很有趣,因爲它使用技巧來存儲對保留解析前向引用所需信息的虛擬對象的引用。這個虛擬對象也可以容納侵入鏈。 在我的系統中,所有可序列化的類繼承自基類Serializable,它可以有一個方法來解析前向引用。該實現可以遍歷所有引用,如果它們引用一個虛擬Serializable對象,則使用其包含的信息來解析該鏈接。 是這個想法嗎?無論如何,這是非常好的。 – chmike 2010-02-05 15:08:49