Builder Pattern in Typescript Similar to Java - chaining in parent class

46 Views Asked by At

I am trying to implement TicTacToe game in typescript. In this, the class HumanPlayer and BotPlayer inherit ab abstract class Player.

To create the instance of HumanPlayer and BotPlayer - using Builder pattern.

enum TicTacToeSymbol {
    O="O", X="X"
};

abstract class Player {
  public symbol!: TicTacToeSymbol;
  abstract makeMove(): void;

  public getSymbol(): TicTacToeSymbol {
      return this.symbol;
  }

  public setSymbol(symbol: TicTacToeSymbol) {
      this.symbol = symbol;
      return this;
  }
}

In the above Player class, to reduce the code duplication, i've kept the common attribute symbol and its getter and setter.

class HumanPlayer extends Player {
    name!: string;

    constructor() {
        super();
    }

    makeMove(): void {
        console.log('make a move');
    }

    public static builder() {
        return new HumanPlayer.Builder();
    }

    static Builder = class Builder extends HumanPlayer {
        public setName(name: string) {
            this.name = name;
            return this;
        }

        public build() {
            const game = new HumanPlayer();

            game.name = this.name;

            return game;
        }
    }
}

But when i try to use it like this -

const humanPlayer = HumanPlayer.builder().setName("XYZ").setSymbol(TicTacToeSymbol.X).build();

console.log(humanPlayer); // HumanPlayer: {"name": "XYZ" } 

But its not setting the symbol. One solution i have in mind is to move the setter and getter in the child class i.e Human and Bot player, but that will have code duplication.

Is there any other way we can achieve this?

0

There are 0 best solutions below