ts的面向对象,用接口实现类后怎么统一调用?

作者站长头像
站长
· 阅读数 13

上代码

type mapType = string

interface ILayer {
  readonly type: "pointIcon" | "point" | "pointSpiIcon"
}

interface IDrawConstructor {
  map: mapType
  layer: ILayer
  addPoint: (map: mapType, layer: ILayer) => void
}

interface IDrawPointConstructor {
  map: mapType
  layer: ILayer
}

// 实现接口
class DrawIconPoint implements IDrawConstructor {
  public layer: ILayer;
  public map: mapType;

  constructor(map: mapType, layer: ILayer) {
    super()
    this.map = map
    this.layer = layer
  }

  addPoint(map: mapType, layer: ILayer): void {
    console.log('iconPoint')
  }
}

// 实现接口
class DrawSpiritIconPoint implements IDrawConstructor {
  public layer: ILayer;
  public map: mapType;

  constructor(map: mapType, layer: ILayer) {
    super()
    this.map = map
    this.layer = layer
  }

  addPoint(map: mapType, layer: ILayer): void {
       console.log('iconSpiritPoint')
  }
}


// 导出统一类
export class DrawPoint implements IDrawPointConstructor {
  public map: mapType
  public layer: ILayer

  constructor(map: mapType, layer: ILayer) {
    this.map = map
    this.layer = layer
    layer.type === 'pointIcon' ?
      new DrawIconPoint(map, layer) : new DrawSpiritIconPoint(map, layer)
  }
}

现在想的是 只用 new 一个类 DrawPoint,然后传入参数,就能自动执行里面的实现类

现在是通过 if 判断来实现,考虑到后续会有 if 判断的条件增加,要手动来这里修改if的条件,有没有什么更好的实现方式

回复
1个回答
avatar
test
2024-07-17
  1. 没必要写这么多 interfaceimplements,直接在类上定义属性和类型即可,TypeScript 能够推断出你的类上到底有什么
  2. 通过修改构造函数的返回值,确实可以做到 new A() 但是返回一个 B 的实例,但是为什么要用这种 hack 的方式?直接一个函数不就行了?
  3. 如果不想用 if else,那么就用模式匹配,switch,或者用对象,你的判断条件是一个字符串,可以以判断条件为键,回调函数为值构建一个对象,比如:
const obj = {
    pointIcon(map, layer) {
        return new new DrawIconPoint(map, layer)
    },
    pointSpiIcon(map, layer) {
        new DrawSpiritIconPoint(map, layer)
    }
}
obj[layer.type](map, layer)
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容