开发者

Exchanging data between classes

I have a main class called Main, in that Main class there is an variable called State which is of int type. State variable contains a state ID which lets the program know in which state is it in (Menu, instructions screen...) In the Main class I have a object initiated from the Sprite class. Now 开发者_如何学JAVAmy question is how to tell the object that the state has been switched (this one is easy, I can make this one pretty easily but the next part is giving me problems), and how can the object tell the Main class that he wants to switch states?


This is what I understand from your question,

  • Main is the controller class that invokes Sprite instance methods
  • The State determines the method that is called on the Sprite instance

In this case, the Sprite class should contain a static property called State (preferably this should be an enum rather than an int).

It is the responsibility of the instance methods to update the state variable. On completion of execution of the instance method, the caller can check the state the instance is in and then appropriately determine the next course of action.

A better approach is not to expose the state at all (unless it is required to be used by external objects). In your case, it appears that the state is only being used to determines the method that executes (I am guessing that you have a switch statement to do this).

If you want to instance to execute a particular method based on its own state, then you could leave this decision to the instance itself, rather than having the controller decide. The instance could have a method (say Update() or Execute()) that execute the operation based on the context of the operation (like menu option, etc.). This method can decide which internal method to execute based on the static state member.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜