现在,我一直在尝试更好地构建代码结构,并专注于在代码中越来越多地使用OOP概念。
我有一个关于以下场景的简单问题,以及如何从设计模式的角度最好地解决它。
我有一个游戏,玩家可以在其中抢劫商店。商店由Shop
对象表示,抢劫由RobEvent
表示。我有一个Spawner
对象,用于当有人试图抢劫商店时处理证券的产生。
我的中心问题是,我感到RobEvent
对象具有下面所述的太多信息和功能,并且我可以将信息和功能拆分为更多的对象,为此,我需要您的帮助!
public class Main
{
public static void main(String[] args)
{
}
public class Shop {
private String name;
private Location location;
private boolean isBeingRobbed = false;
/*
* Here one of the problems, should the shop have the
* data of the npcs, which will appear
* in the shop when the player attempts to rob it.
* Should it have methods to place "spawn" positions of
* the securities, the type, the amount etc.
* and store it here?
*
*/
public Shop(String name, Location location){
this.name = name;
this.location = location;
}
public boolean isBeingRobbed(){
return isBeingRobbed;
}
protected void setBeingRobbed(boolean bool){
this.isBeingRobbed = bool;
}
}
public class RobEvent extends Looper {
private Shop shop;
RobEvent(Shop shop){
this.shop = shop;
}
public void start(){
shop.setBeingRobbed(true);
}
@Override
protected void logic(){
/*
* Big chunk of game logic
* Spawning the securities, checking if they
* all appeared(they got a delay of few seconds each),
* check if he ran away before everything
* spawned, check if he killed all, check if all appeared
*/
}
private void completed(){
shop.setBeingRobbed(false);
}
}
public class Spawner {
/* not important things
*
* just has a method to
* handle the spawn of a security
*/
public void spawn(NPC npc){
/*
* spawn the npc aka security
*/
}
}
}
我最大的问题是
logic()
方法变得很大。这是一个方法,它由超类每秒循环。更多详情:
RobEvent
必须知道它当前是否正在产生证券并做特定的事情,它必须检查是否都产生了并执行特定的操作,
它必须检查玩家是否在完成之前逃跑并做一些特定的事情,
它必须检查玩家是否杀死了所有人并做特定的事情等。
最烦人的是跟踪生成的证券,因为如果他逃跑了,则必须全部删除它们。我感觉这在该对象中包含太多信息,例如,我可以将跟踪生成的证券拆分到一个单独的对象中,并在
tracker.despawn
具有特定状态时执行类似RaidEvent
的操作。编辑:代码是对实际代码的真正简化。
最佳答案
RobEvent必须知道它当前是否正在产生证券并做特定的事情,-它必须检查是否都产生了证券并做特定的事情,-它必须检查玩家是否在完成之前逃跑并做特定的事情,-它必须检查玩家是否杀死了所有人并做特定的事情等。
这听起来像State-Pattern,它将逻辑与状态分离。
快速实施RobEvent
需要跟踪RobState
。您有多个RobState
,例如StartSpanSecuritiesState
,AllSecuritiesSpanedState
,PlayerRunAwayState
等。
interface RobState {
void handle();
}
class RobEvent extends Looper implements RobState {
// add new member
private RobState robState;
private Shop shop;
RobEvent(Shop shop) {
this.shop = shop;
this.robState = new StartSpanSecuritiesState();
}
// add new setter - gets normally called only by a `State`
void setRobState(RobState robState) {
this.robState = robState;
}
// ..
}
每个
RobState
都知道下一个RobState
,并通过setRobState
的RobEvent
进行设置。class StartSpanSecuritiesState implements RobState {
private RobEvent robEvent;
public StartSpanSecuritiesState(RobEvent robEvent) {
this.robEvent = robEvent;
}
@Override
public void handle() {
// span your securities
//...
// go to the next state
robEvent.setRobState(new AllSecuritiesSpanedState(robEvent));
}
}
完成所有修改后,
logic
方法可能类似于:@Override
protected void logic(){
robState.handle();
}
希望对您有帮助!如果不是这个时候,也许将来!
玩游戏吧:]