我認爲你正在尋找的答案是「單身模式」。這是您創建一個類的一個實例在其他地方使用的地方。這是一個good link to read。這裏有一些java示例的wikipedia page on it。
所以您的代碼會是這個樣子:
public class A {
private final static A instance = new A();
/* private constructor forces you to use the getInstance() method below */
private A() {}
public static A getInstance() {
return instance;
}
}
那麼無論你想,你會做這樣的事情一個實例:
public class B {
private final A classA = ClassA.getInstance();
...
}
沒有理由A
可能也不具有B
的實例,並在其自己的方法中調用B
的方法。你無法用這個交叉依賴關係調用構造函數中其他方法的任何一個。
一般來說,順便說一句,這些模式應該謹慎使用。更好的方法是通過依賴注入來代替全局引用。交叉注射是可能的,但同樣應該謹慎使用。更好的解決方案是重構類以獲得線性依賴關係。
Java中是否有任何概念將引用作爲變量的對象的實際對象(如指針)而不是製作對象的副本?
Java是傳值但任何對象的值是參照對象(類似於在C指針儘管它們不一個存儲器地址)。因此,如果您有A
的實例並將其分配給另一個字段,則該字段將具有相同的值,並且將引用同一個A
實例。
// instantiate a new instance of A
A a1 = new A();
// assign the reference to A to another variable
a2 = a1;
// they are equivalent and both reference the same object
if (a1 == a2) ...
談不好的設計.. – mre
(ObPlead:請,請不要使用mutable statics(以前稱爲全局變量),這包括使用singleton反模式) –