public interface UnitMgr {
}
import mgr.UnitMgr;
public class A implements UnitMgr{
private static UnitMgr instance = new A();
private B b = (B) B.getInstance();
public static UnitMgr getInstance(){
if(instance == null){
instance = new A();
}
return instance;
}
}
import mgr.UnitMgr;
public class B implements UnitMgr{
private static UnitMgr instance = new B();
private A a = (A) A.getInstance();
public static UnitMgr getInstance(){
if(instance == null){
instance = new A();
}
return instance;
}
}
public class Test{
public static void main(String[] args) {
A.getInstance();
B.getInstance();
}
像上面Test主类调用测试那样,就会出现java.lang.StackOverflowError错误,原因就是循环迭代调用,即,A调用B, B调用A,所以在使用单例的时候,最安全的方法就是别将一个单例定义成另一个单例的属性,而是直接getInstance()调用。