Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created May 3, 2020 11:23
Show Gist options
  • Save armanozak/86c868da4cad328162e863cf19d3ed48 to your computer and use it in GitHub Desktop.
Save armanozak/86c868da4cad328162e863cf19d3ed48 to your computer and use it in GitHub Desktop.
[Strategy Pattern with TypeScript] After Implementation #blog #typescript
abstract class Hero {
constructor(public name: string, public weapon?: string) {}
abstract attack(): void;
}
class BlastingHero extends Hero {
attack() {
console.log(`${this.name} blasted ${this.weapon}.`);
}
}
class ShootingHero extends Hero {
attack() {
console.log(`${this.name} shot ${this.weapon}.`);
}
}
class ThrowingHero extends Hero {
attack() {
console.log(`${this.name} threw ${this.weapon}.`);
}
}
class UnarmedHero extends Hero {
attack() {
console.log(`${this.name} kicked and punched.`);
}
}
class Avengers {
private ensemble: Hero[] = [];
recruit(hero: Hero) {
this.ensemble = this.ensemble
.filter(({name}) => name === hero.name)
.concat(hero);
}
fight() {
this.ensemble.forEach(hero => hero.attack());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment