当前位置: 代码迷 >> Ruby/Rails >> 类的相互依赖以致StackOverflowError
  详细解决方案

类的相互依赖以致StackOverflowError

热度:142   发布时间:2016-04-29 02:22:57.0
类的相互依赖导致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();	}}

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

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

  相关解决方案