使用傳統的偵聽器回調模型。我有幾個聽衆收集各種東西。每個偵聽器收集的內容都在內部結構的偵聽器中。正確耦合需要訪問共享狀態數據的多個偵聽器
的問題是,我想一些聽衆要注意的一些在其他聽衆的「東西」。
我執行偵聽器註冊順序,所以如果我明知註冊以某種順序事件後聽衆可以肯定的是先前聽衆更新了東西,並以某種方式訪問它做更多的東西。
我在第一次嘗試讓每個聽者存儲其所依賴聽衆的參考。因此,我按照沒有依賴關係的順序將偵聽器註冊到那些具有預先註冊依賴關係的偵聽器中,然後用各種方法在偵聽器之間設置引用。
我開始意識到多麼糟糕這感覺,我想知道,如果不知何故以前一直沿着這條道路。當其中一位聽衆需要訪問另一位聽衆時,什麼會是更合適的模式?
下面是一些僞代碼來說明:
interface Listener { onEvent(char e); }
class A implements Listener {
private int count;
public void onEvent(char e) { if(e == 'a') count++; }
public int getCount() { return count; }
}
class B implements Listener {
private int count;
// private A a;
// private void setA(A a) { this.a = a; }
public void onEvent(char e) { if(e == 'b') count++; }
public int getCount() { return count; }
public int getAPlusBCount() {
// We know B count, but we don't know A so how would we change this
// so B is A aware? Or not even aware, just somehow coupled? This
// is the question
// return a.getCount() + count;
}
public void doConditionalHere() {
// Do some condition in B that relies on the state of data in A
int acount = 0; // a.getCount(); ???
if(acount % 2 == 0) {
this.count--;
}
}
}
class Run {
A a = new A();
B b = new B();
List listeners = new List();
listeners.add(a);
listeners.add(b);
// The ugly way I add coupling right now is to keep a reference to A
// inside B. It's commented out because I am hoping there is a more intelligent approach
// b.setA(a);
for(char c : "ababbabab") {
for(listener : listeners) {
listener.onEvent(c);
}
}
}
「我要繼續前進,並接受你的答案,因爲它的工作原理,但我希望爲一些其他的方式。」這很愚蠢。爲什麼接受它?爲什麼不等待更好的答案? – 2008-11-10 02:53:56
好的,我會等的。 – Josh 2008-11-10 14:36:06