类的相互依赖导致StackOverflowError

前端之家收集整理的这篇文章主要介绍了类的相互依赖导致StackOverflowError前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public class SchoolServiceImpl {
	private static SchoolServiceImpl instance = new SchoolServiceImpl();
	private static ClassServiceImpl classServiceImpl = ClassServiceImpl.getInstanse();	
	public static SchoolServiceImpl getInstanse() {
		if (instance == null)
			return instance = new SchoolServiceImpl();
		return instance;
	}

	public int getSchoolCount() {		
		return classServiceImpl.getClassesCount();
	}
    
	public static void main(String[] args) {
		System.out.println(classServiceImpl.getClassesCount());
	}
}

public class ClassServiceImpl {

	/**
	 * @param args
	 */	
	private static ClassServiceImpl instance = new ClassServiceImpl();
	public static  ClassServiceImpl getInstanse() {
	if (instance == null)
			return instance = new ClassServiceImpl();
		return instance;
	}
	private static SchoolServiceImpl schoolServiceImpl=SchoolServiceImpl.getInstanse();
	
	public int getClassesCount()
	{   
		System.out.println(classServiceImpl.toString());
		return schoolServiceImpl.getSchoolCount();
	}
}

如上两个类彼此依赖其中的方法,导致死循环,最终导致内存溢出。

从中得到的教训:尽可能减少类的彼此依赖,做到单向依赖。

猜你在找的设计模式相关文章