Javascript 强制子类不可变
我有一个具有一些属性的基类:Javascript 强制子类不可变,javascript,oop,typescript,design-patterns,immutable.js,Javascript,Oop,Typescript,Design Patterns,Immutable.js,我有一个具有一些属性的基类: class Component { readonly id: number readonly type: number } 我想要一些子类: class HealthComponent extends Component { max_health: number, current_health: number } etc. 我想要的本质是使HealthComponent具有与不可变组件相同的行为。Record: const he
class Component {
readonly id: number
readonly type: number
}
我想要一些子类:
class HealthComponent extends Component {
max_health: number,
current_health: number
}
etc.
我想要的本质是使HealthComponent
具有与不可变组件相同的行为。Record
:
const health = HealthComponent(100, 100);
health.max_health = 40; // Shouldn't work
const new_health = new HealthComponent(40, health.current_health); // Works
所有的类都只是数据;没有行为(如果有任何行为,它将在静态方法中,而不是在实例方法中)。现在我想尽可能地强制子类是不可变的(在这个意义上,允许修改,但进行更改会导致新对象或抛出一个错误a la immutable.js),我无法找到最好的方法来做到这一点
t我想到的最好的办法是让每个子类都有一个只读的数据
成员,它是一个不可变的。用适当的字段记录
,但即使这样也不太正确,因为更改它会返回一个新的数据
对象,但我真的想要一个全新的组件
对象,这也不能强制所有组件都遵循这个约定
我考虑过的另一件事是让基类是一个不可变的。使用data:Immutable.Map
字段记录,然后子类提供一个不可变的。将映射到超级构造函数,并使用所有键,但是人们可以随意添加新键,这也不理想
这里有没有一种神奇的设计模式可以帮助我?使用只读
那是一段相当难理解的段落。通常最好将段落限制在2-3句,然后是一个新段落(在合理范围内)。
class Component {
constructor(public id: number, public type: number) {
}
}
class HealthComponent extends Component {
constructor(public id: number, public type: number, public max_health: number, public current_health: number) {
super(id, type);
}
}
let hc: Readonly<HealthComponent> = new HealthComponent(1, 2, 3, 4);
hc.max_health = 40; // Error
interface Component {
id: number
type: number
}
interface HealthComponent extends Component {
max_health: number;
current_health: number;
}
let hc: Readonly<HealthComponent> = {
id: 1,
type: 2,
max_health: 3,
current_health: 4
};
hc.max_health = 40; // Error