参考: https://blog.csdn.net/m0_37450089/article/details/81607363
类的依赖处理
示例代码用ts
一、不采用接口
class Car {
constructor() {
this.ligng = new Light()
this.engin = new Engin()
}
// 刹车
brake() {
this.light.blink()
this.engine.stop()
}
}
// 车灯
class Light {
blink() {
console.error('刹车灯闪烁...')
}
}
// 车发动机
class Engine {
stop() {
console.error('发动机熄火...')
}
}
let car = new Car()
car.brake()
缺点:
- 类之间强耦合
二、采用接口
interface StopInerface {
// 引擎熄火
stop(): void
// 刹车灯闪烁
blink(): void
}
class Car {
// 刹车
brake(i: StopInerface) {
i.blink()
i.stop()
}
}
class Light implements StopInerface{
constructor() {}
blink() {
console.error('刹车灯闪烁...')
}
// 必须实现接口
stop() {}
}
class Engine implements StopInterface{
// 必须实现接口
blink() {}
stop() {
console.error('发动机熄火...')
}
}
let car = new Car()
let light = new Light()
let engine = new Engine()
car.brake({
blink: light.blink,
stop: engine.stop
})
缺点:
- 客户端使用自己用不到的方法
三、采用接口隔离
interface LightStopInerface {
blink(): void
}
interface EngineStopInterface {
stop(): void
}
class Car {
constructor() {}
// 刹车
brake(light: LightStopInerface, engine: EngineStopInterface) {
light.blink()
engine.stop()
}
}
class Light implements LightStopInerface{
constructor() {}
blink() {
console.error('刹车灯闪烁...')
}
}
class Engine implements EngineStopInterface{
constructor() {}
stop() {
console.error('发动机熄火...')
}
}
let car = new Car()
let light = new Light()
let engine = new Engine()
car.brake({blink: light.blink}, {stop: engine.stop})
<全文结束>