上代码
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的条件,有没有什么更好的实现方式
interface
和implements
,直接在类上定义属性和类型即可,TypeScript 能够推断出你的类上到底有什么new A()
但是返回一个B
的实例,但是为什么要用这种 hack 的方式?直接一个函数不就行了?if else
,那么就用模式匹配,switch
,或者用对象,你的判断条件是一个字符串,可以以判断条件为键,回调函数为值构建一个对象,比如: