【问题标题】:Android: Communicating with common functions regardless of ClassAndroid:与常用功能进行通信,而不考虑类
【发布时间】:2019-03-20 15:33:53
【问题描述】:

我有一个不同关卡的游戏,关卡之间有很多共享代码。所以我有包含所有共享代码的 MainActivity,这会为每个级别加载一个片段 LevelOne,其中包含特定于级别的代码。我需要使用片段,因为我还加载了其他带有其他 UI 组件的片段。

关卡片段都包含同名的函数,每个关卡都有唯一的代码,例如StartGame() 和 PauseGame(),MainActivity 在必要时调用它们。如何加载允许我访问这些功能的单个对象,而不管它是什么片段?

例如在 python 中我会这样做:

// Instantiation
int level_number = 1;  
levels = [levelOne, levelTwo]
level = levels[level_number]

// Something happens and I want to start the currently selected level somewhere in MainActivity
level.StartGame()      

但在 Java 中我不能这样做,因为我必须事先指定对象的类,我不知道,相反,如果我提到级别的任何地方的条件,我都必须有这些:

// Instantiation
LevelOne levelOne = new LevelOne();  
LevelTwo levelTwo = new LevelTwo();

// Something happens and I want to start the currently selected level somewhere in MainActivity    
if (level_number == 1) {
   levelOne.StartGame();
} elif (level_number == 2) {
   levelTwo .StartGame();
}

【问题讨论】:

    标签: java android oop android-fragments


    【解决方案1】:

    为什么每个级别都需要另一个课程?

    Level levelOne = new Level(1);  
    Level levelTwo = new Level(2);
    

    【讨论】:

    • 因为每个班级都有明显不同的代码(每个级别本质上是不同的游戏)
    • @James 你仍然可以有一个抽象类BaseLevelFragment 然后LevelOne extends BaseLevelFragment... 这应该会大大减少代码冗余,同时允许每个级别的自定义方法实现。只需区分它们的共同点和不同点。
    • 对,所以你的意思是不是 MainActivity 有 BaseLevelFragment,它将包含所有常用代码?
    • @James 定义public abstract class BaseLevelFragment 并将这些片段共有的代码移入其中。关键字abstract 阻止了它的直接实例化,因为只有特定的实现很重要......并且可以使用那里的常用方法,就像它们在同一个类中一样;至少在范围为 protected 时。
    • @MartinZeitler,这并不能解决最初的问题,因为我需要在 MainActivity 中的公共代码引用它时定义 LevelOne levelOne?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2021-06-14
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多