我有一个类在getter / setter中有几个具有相同模式的属性。我不想复制样板,但我不确定如何。
有没有办法在下面的示例类中使用装饰器或其他语言功能来实现这一点?
export class Reaction {
// These two properties have the same getter/setter pattern
private _reactant1: State = null;
get reactant1(): State {
return this._reactant1;
}
set reactant1(newState: State) {
if (this._reactant1) {
this.deregister(this._reactant1);
}
this._reactant1 = newState;
if (this._reactant1) {
this.register(newState);
}
}
private _reactant2: State = null;
get reactant2(): State {
return this._reactant2;
}
set reactant2(newState: State) {
if (this._reactant2) {
this.deregister(this._reactant2);
}
this._reactant2 = newState;
if (this._reactant2) {
this.register(newState);
}
}
constructor(reactant1?: State,
reactant2?: State) {
if (reactant1) {
this.reactant1 = reactant1;
}
if (reactant2) {
this.reactant2 = reactant2;
}
}
register(state: State) {
if (state) {
console.log('do a thing')
}
}
deregister(state: State) {
if (state) {
console.log('do a thing')
}
}
}