我有两个类灯和开关。由于我已经在不同的文件中分离了这两个类,现在我有一个自相矛盾的导入:
-
灯导入开关呼叫开关(本(
-
交换机导入灯以解析其接口。
灯.ts
import Switch from './switch.ts';
export default class Lamp {
state: 'on' | 'off' = 'off';
constructor () {
Switch.on(this);
}
}
开关
import Lamp from './lamp.ts';
export default class Switch {
static on (lamp: Lamp) {
lamp.state = 'on';
}
static off (lamp: Lamp) {
lamp.state = 'off';
}
}
你可以创建一个接口,我们称之为Switchable
。Lamp
可以实施。
这样Switch
依赖于抽象而不是具体的Lamp
类。
它看起来像这样:
interface Switchable {
state: 'on' | 'off';
}
class Lamp implements Switchable {
state: 'on' | 'off' = 'off';
constructor() {
Switch.on(this);
}
}
class Switch {
static on(switchable: Switchable) {
switchable.state = 'on';
}
static off(switchable: Switchable) {
switchable.state = 'off';
}
}
这是带有代码的操场链接。