lundi 29 mai 2017

Forcing Subclasses to Be Immutable

I have a base class with some properties:

class Component {
    readonly id: number
    readonly type: number
}

And I'd like to have some subclasses:

class HealthComponent extends Component {
    max_health: number,
    current_health: number
}

etc.

What I want is essentially for HealthComponent to have the same behavior as an Immutable.Record:

const health = HealthComponent(100, 100);
health.max_health = 40; // Shouldn't work
const new_health = new HealthComponent(40, health.current_health); // Works

All of the classes are just data; no behavior (if there is any behavior, it will be in static methods, not instance methods). Now I want to enforce as much as possible that the subclasses are immutable (in the sense that modifications are allowed, but making changes results in a new object a la Immutable.js) and I can't figure out the best way to do this. So far the best thing I've come up with is to just have each subclass have a readonly data member that is an Immutable.Record with the appropriate fields, but even this isn't quite right because changing it would return a new data object, but I really want a whole new Component object, and this also doesn't really enforce that all components follow this convention. The other thing I've considered is to have the base class be an Immutable.Record with a data: Immutable.Map field and then the subclasses provide an Immutable.Map to the super constructor with all the keys, but then people could just add new keys willy nilly which isn't ideal either.

Is there a magic design pattern that could help me here?

Aucun commentaire:

Enregistrer un commentaire