Created
May 3, 2020 11:23
-
-
Save armanozak/86c868da4cad328162e863cf19d3ed48 to your computer and use it in GitHub Desktop.
[Strategy Pattern with TypeScript] After Implementation #blog #typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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