Skip to content

Instantly share code, notes, and snippets.

@theScottyJam
Last active November 10, 2021 15:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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