java—如何在多个类中使用来自父类对象的结果

qlvxas9a  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(257)

我把帖子编辑得更清楚一点。在我的程序中有两个.java文件。
java中,我最终希望创建一些返回布尔结果的方法。见下文(这只是为了模拟结果):

public class IoInterface{
   //let just say reading a button press that return true
     public boolean getDigitalInput(){
       boolean result = true;
       return result;
     }
   }

下一个是statemachine.java。在这一次我经历了几个州。例如,在每个状态下,我都希望从getdigitalinput()访问结果。

public class StateMachine extends IoInterface  {

  public static void main(String[] args) {

        IoInterface io = new IoInterface();

        State.firstState = new firstState();
        State.secondState = new secondState();
        State.thirdState = new thirdState();

    //on startup move to first state
    State.currentState = State.firstState;

    while (true) {
      State.currentState.enter();
      State.currentState.update();
    }
  }
}

// code starts in this state
class firstState extends State {
 // here i need to read the result from IoInterface.java -> getDigitalinput method
 // bool buttonPress= io.getDigitalInput();  this doesnt work

 void enter() {
// while in this state do something
}

 void update() {
//move to new state if button is pressed
 if (buttonPress = true){
currentState = secondState}
   }   
}

abstract class State {
  static State firstState, secondState, thirdState, currentState;

  void enter() {}

  void update() {}

}
zqdjd7g9

zqdjd7g91#

如果你要解决的问题是如何用一个信号正确地触发一个状态,帮助它转换到正确的状态,那么你可能会从我写的一篇关于如何正确实现状态机的博客中受益。
结合状态和单例模式创建状态机
使用状态机控制向导
在第一个例子中,您将看到我如何创建不可变状态对象来表示有限的状态,并使用状态设计模式来控制从状态到状态的转换。在第二个版本中,我扩展了这个实现,使用我的设计来控制一个向导(其中每个“视图”都是一个状态,按钮点击是触发从状态(视图)到另一个(视图)转换的信号)。基本上,第二个博客将设计付诸实践。
如果没有,你将需要明确你要解决的问题。如果您需要一点关于状态模式的背景知识,请阅读本文。
对于您的具体问题,您需要了解适当的责任授权。这不是政府的责任 firstState 类来知道它是应用程序的起点。

class firstState extends State {
 // here i need to read the result from IoInterface.java -> getDigitalinput method
 // bool buttonPress= io.getDigitalInput();  this doesnt work
 // The above lines do not belong here. They belong in the `IoInterface` class (or whichever class contains the button).
 void enter() {
// while in this state do something
}

 void update() {
//move to new state if button is pressed
 if (buttonPress = true){
currentState = secondState}
   }   
}

相关问题