I'm implementing a board game for two players. Users are able to create their own AIs for the game and add them to the game. These AIs also can implement own, more efficient versions (data structures) of the board to save time when calculating the next move. The HumanPlayer and a simple Board are implemented by me.
To be able to make moves on the different boards from a central Game class and check moves in a given Referee, all classes which shall interact with the board have to inherit from the abstract class Actor.
public abstract class Actor<BoardClass extends IBoard> {
protected BoardClass board;
public void makeMove(Move move) {
board.movePiece(move);
}
}
The referenced interface IBoard has to be implemented by any board used in the program. That way, the game will always be able to inform all registered instances of Actor about the made move via following method.
private void informActors(Move move) {
for (Actor<?> actor : actors) {
actor.makeMove(move);
}
}
All implemented players - including the human player implemented by me - have to inherit from the abstract class Player which again has to inherit from the given class Actor.
public abstract class Player<BoardClass extends IBoard> extends Actor<BoardClass> {
//some game specific code
}
The HumanPlayer now inherits from Player and uses my Board class as the type that implements IBoard.
public class HumanPlayer extends Player<Board> {
// some game specific code
}
The exact implementation of my simple Board class and the Referee class do not matter.
To keep redundant code at a minimum, I don't want to instantiate the implementation of Board as the IBoard inheriting type in both the Referee and the Player class, especially since I was able to use interfaces and inherited methods to implement every other "interaction" dynamically.
So, to be precise. I am searching for a dynamic way of instantiating an object from a class, which is only known during runtime, but without using reflection.
I had the idea to create a static method in the IBoard interface which creates an object of that class and returns it and which gets overwritten by the implementing classes, but since static methods use static binding, they do not get bound dynamically during runtime.
The only other option I could think of was reflection, which I don't want to use.
I do know I can use
// replace 'ClassConstructor' with 'Referee', 'HumanPlayer' or any other class inheriting from 'Actor'.
public ClassConstructor() {
this.board = new Board();
}
as the constructor of the Referee and the HumanPlayer, but again, it's bothering me to duplicate that line of code when its maybe possible via a better way.