I am trying to figure out how Factory pattern works. I implemented it with TypeScript in this github repo: https://github.com/emilecollin/factory_pattern
Basically this is emulating spaceships gaming logic: the program will ask you to input in the terminal one of these options: "alien" or "zombie". With the provided input, the program will select on runtime the proper ship class to instantiate (AlienShip or ZombieShip), and a spaceships fight is mocked. The logic for the decision of which spaceship class to instantiate lives in a «factory method».
The abstract creator:
export abstract class AbstractShipFactory {
public abstract makeShip(shipType: string): Ship;
}
The concrete creator:
export class EnemyShipFactory extends AbstractShipFactory {
public makeShip(shipType: string): Ship {
switch (shipType) {
case 'alien':
return new AlienShip();
case 'zombie':
return new ZombieShip();
}
}
}
The Product interface:
export interface Ship {
name: string;
damage: number;
attack(): string;
}
And the Concrete Product class:
export class AlienShip implements Ship {
private _name: string = 'alien';
private _damage: number = 35;
get name(): string {
return this._name;
}
get damage(): number {
return this._damage;
}
attack(): string {
return '---->You are being attacked by ' + this.name + ' spaceship and got a damage of ' + this.damage;
}
}
I'm now sure if I got it right. Still a bit confused about it. Any opinion of this code will be welcome!