g_elef
g_elef

Reputation: 57

Is there a way to cleanly avoid duplicate code in this instance?

I'm working on android with Java and I'm implementing the Model-View-Presenter architecture. There are two types of games the player can play:

Both games are really similar but with each their respective .class documents and (e.g. GameA.class and a GameB.class).

In both cases, their respective presenters are the same, with the only thing changing being the instantiation & declaration of the model class. For example:

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

    }
}

Is there any way I can cleanly avoid having duplicate code, simulated by the single-line comments? Bonus if I can make both models share the one presenter.

Upvotes: 1

Views: 133

Answers (1)

Nizar
Nizar

Reputation: 2254

You are gonna want to create a generic Game class that GameA and GameB can then both inherit from.

Same can go with the GamePresenter, create a generic one that GamePresenterA and GamePresenterB can inherit from. Also you can give the GamePresenter a Game everytime you create a new instance of it or call a certain method. That way there can be a single GamePresenter and it can take whatever Game to present it.

Upvotes: 2

Related Questions