在这种情况下,有没有一种方法可以避免重复代码?

时间:2020-01-15 19:37:09

标签: java android class duplicates mvp

我正在使用Java在android上工作,并且正在实现Model-View-Presenter体系结构。玩家可以玩两种游戏:

  • 游戏A
  • 游戏B

这两个游戏确实非常相似,但是每个游戏都有各自的.class文件和(例如 GameA.class和GameB.class )。

在两种情况下,它们各自的演示者是相同的,唯一改变的是模型类的实例化和声明。例如:

GameAPresenter.class:

class GameAPresenter{

    private GameA game;
    // other stuff here that happens in both presenters

    GameAPresenter(int par1, int par2){
        this.game = new GameA(par1, par2);
        //other stuff here that happens in both presenters

    }
}

GameBPresenter.class:

class GameBPresenter{

    private GameB game;
    // other stuff here that happens in both presenters

    GameBPresenter(int par1, int par2){
        this.game = new GameB(par1, par2);
        //other stuff here that happens in both presenters

    }
}

有什么方法可以完全避免出现由单行注释模拟的重复代码? 如果我可以让两个模型都共享一个演示者,那就可以了。

1 个答案:

答案 0 :(得分:2)

您将要创建一个GameGameA都可以继承的通用GameB类。

Same可以与GamePresenter一起使用,创建GamePresenterAGamePresenterB可以继承的通用变量。另外,每次创建新实例或调用某个方法时,都可以给GamePresenter一个Game。这样,可以只有一个GamePresenter,并且可以花任何Game来呈现它。