jeudi 8 avril 2021

How can I dress/undress (add/remove properties) a class instance without wrapping in another class?

Background: I have a class whose instances need a few additional properties when it's used in a different context. My current solution looks a bit like this:

class Horse {
    speed = 1
}

class RaceHorse {
    constructor(raceNumber, horse) {
        this._horse = horse
        this.raceNumber = raceNumber
    }
}

const horse = new Horse()

// When a race is ongoing, which is a temporary state, I wrap it like so:
// const raceHorse = new RaceHorse(3, horse)

I.e. a horse can exist in "normal" contexts as well as in race contexts. It only needs the raceNumber in a race contexts, and it wouldn't make sense to include it when the horse is not in a race. My real use-case is more complex and includes references to other class instances which only exists in the race context.

In other words, I use a wrapper class to extend the horse - kind of like dressing it up. My current solution is cumbersome and doesn't feel elegant at all. My real-world scenario also contains a lot more classes that I need to wrap like this in order to add various contextual properties.

My question is: Are there other ways of doing this? Smarter programming patterns that can be applied?

Aucun commentaire:

Enregistrer un commentaire