【发布时间】:2016-08-07 01:43:17
【问题描述】:
我的程序中有一个无限递归,我在一个类中有一个字段,该字段在其字段中具有相同的类。它们是单例,但这不是导致它们不构造的原因。顺便说一句,我编写程序实际上无法删除阶段数组。
abstract class Phase{
protected String phaseName;
protected char[] keys;
protected String[] commands;
protected Phase[] phases;
protected StringBuilder pattern;
}
class RemotePhase extends Phase{
private static RemotePhase remotePhase;
protected RemotePhase(){
phaseName="Remote.";
commands=new String[]{"Lock/unlock windows", "Toggle door", "Select dog menu"};
setPattern();
//Just below here starts an infinite loop
phases=new Phase[]{FixWindows.getFixWindows(), ToggleDoor.getToggleDoor(), SelectDogPhase.getSelectDogPhase()};
}
public static RemotePhase getRemotePhase(){
if(remotePhase==null){
remotePhase=new RemotePhase();
}
return remotePhase;
}
}
final class FixWindows extends Phase{
private static FixWindows windows;
private RemotePhase remotePhase;
private FixWindows(){
//execution keeps coming here as FixWindows object is never constructed
remotePhase=RemotePhase.getRemotePhase();
}
public static FixWindows getFixWindows(){
if(windows==null){
windows=new FixWindows();
}
return windows;
}
}
我尝试将 RemotePhase 设为静态类,FixWindows 将其用于其成员,但在尝试覆盖抽象类的非静态方法并尝试在非静态上下文中从 FixWindows 调用它们时遇到了错误。不过我更喜欢不让它成为静态的,因为我必须创建一个额外的类来引用 RemotePhase。
尽管有任何方法可以使这项工作。谢谢
【问题讨论】:
-
这是一个无限递归而不是无限循环。
-
更改
FixWindows构造函数并传递RemotePhase(this) 以在getFixWindows中构建它,或者只是在getFixWindows中设置remotePhase。尽量避免在其他构造函数中调用构造函数。你的静态方法很适合设置这些东西 -
请出示一下好吗
-
查看this answer 了解实现单例的简单方法
-
谢谢,提醒我在一篇文章中看到了这个策略
标签: java oop design-patterns object-oriented-analysis infinite-recursion