标签:style http io color ar sp java div on
原文地址:http://leihuang.net/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 !
标签:style http io color ar sp java div on
原文地址:http://blog.csdn.net/speedme/article/details/41145125