Article: Composition Alone Can't Replace Inheritance - strategy pattern
This file contains 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
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