我有一個上下文對象有幾個有用的屬性和方法。其他對象在構造函數中接受這個上下文對象。但是,上下文對象可以將這些其他對象作爲公共屬性。請看下圖:對象A具有對象B的引用,該對象具有對象A作爲公共屬性 - 不良設計?
public class Foo {
private IContext Context { get; private set; }
public Foo(IContext context) {
Context = context;
}
}
public class SomeContext : IContext {
public Foo SomeProperty { get; set; }
/*
Other useful properties and methods as defined in IContext
*/
public SomeContext() {
SomeProperty = new Foo(this);
}
}
現在我可以做一些有用的方法上富:
public void FooIt() {
IUseful bar = this.Context.GetUsefulInterface();
bar.DoUsefulThing();
}
但是,它可能會導致一些非常奇怪的東西。考慮Foo上的這些方法:
public void DoSomething() {
/* useful stuff */
}
public void DoSomethingElse() {
this.Context.SomeProperty.DoSomething(); // could just call this.DoSomething();
this.Context.SomeProperty.DoSomethingElse(); // stack overflow!
}
這是否被認爲是糟糕的設計/代碼氣味?背景對象的原因有些涉及,我想更多地將問題提到循環參考。如果認爲不好,有什麼方法打破這種週期性關係?
爲什麼循環引用通常一個代碼味道? – zneak 2011-03-22 18:36:42
因爲如果循環引用比「單向」引用更難維護。我經常見到使用循環引用的buggy實現,並在另一個模式以相同效率解決問題的場景中使用。 – TcKs 2011-03-23 10:47:30