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

上代码

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.4k
1 个回答
  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)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题