Skip to content

Instantly share code, notes, and snippets.

@theScottyJam
Last active November 10, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theScottyJam/62fd98142c843a0d52f9cd128aac865c to your computer and use it in GitHub Desktop.
Save theScottyJam/62fd98142c843a0d52f9cd128aac865c to your computer and use it in GitHub Desktop.
Article: Composition Alone Can't Replace Inheritance - strategy pattern
class Monster {
#onAttack
constructor({ dropLoot, onAttack, customBehaviors = {} }) {
this.dropLoot = dropLoot
this.#onAttack = onAttack ?? (() => {})
this.behaviors = customBehaviors
}
attack() {
playHurtAnimation()
this.#onAttack()
}
die() {
userInventory.add(this.dropLoot())
removeFromUi(this)
}
}
const slimeBehavior = { ... }
const skeletonBehavior = { ... }
const clownBehavior = {
dropLoot() {
return [new Key()]
},
onAttack() {
if (itsTime()) {
showCutScene()
}
},
customBehaviors: {
uniqueClownBehavior() {
...
}
},
}
export const createSlime = () => new Monster(slimeBehavior)
export const createSkeleton = () => new Monster(skeletonBehavior)
export const createClown = () => new Monster(clownBehavior)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment