java對象循環相依性問題,java對象依賴
原文地址:http://leihuang.org/2014/11/13/Cycular-Dependency/
假設我們有一個類A,它包含了一個B的對象,同時類B也包含了一個A對象。那麼此時不管你執行個體化哪一個類,都會出現StackOverflowError錯誤,這就是java對象循環相依性問題。類似於雞和蛋的問題。
首先我們看下面這段錯誤的代碼,分析其錯誤的地方。
public class CyclicDependencies { public static void main(String args[]){ Chicken c = new Chicken() ; //Egg e = new Egg() ; }}class Chicken{ private Egg e ; private int age ; public Chicken(){ e = new Egg() ; setAge(10) ; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}class Egg{ private Chicken chicken ; private int weight ; public Egg(){ chicken = new Chicken() ; setWeight(1) ; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; }}
Exception in thread "main" java.lang.StackOverflowError
這是上面代碼報的錯誤,因為當你建立一個Chicken對象時,同時也需要一個Egg對象,而一個Egg對象也需要一個Chicken對象,這樣一直迴圈下去就發生了棧溢出的錯誤。
那麼如何來解決這個問題呢?我們可以給Chicken寫一個代理類ChickenProxy,這樣Egg包含的不再是Chicken而是代理類ChickenProxy,這樣就利用了第三方來解決循環相依性問題。代碼如下。
public class CyclicDependencies { public static void main(String args[]){ Chicken c = new Chicken() ; Egg e = new Egg(c) ; System.out.println(c.getAge()); System.out.println(e.getWeight()); }}interface ChickenProxy{ int getAge(); void setAge(int age) ;}class Chicken implements ChickenProxy{ private Egg e ; private int age ; public Chicken(){ e = new Egg(this) ; setAge(10) ; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}class Egg{ private ChickenProxy chicken ; private int weight ; public Egg(Chicken c){ chicken = c ; setWeight(1) ; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; }}
2014-11-13 15:41:41
Brave,Happy,Thanksgiving !