我将解释如何在我的代码中执行此操作,但需要说明的是,这种方法比较主观,您可能不喜欢。
首先,我使用标准的ES6
import
和
export
。 我会让所有形状都在同一个文件夹中,并与该文件夹中的
index.ts
文件一起提供导出。 因此,我的结构可能如下所示:
|-- src/
| |-- shapes/
| | |-- index.ts
| | |-- IShape.ts
| | |-- Rectangle.ts
| | |-- Circle.ts
| | |-- Triangle.ts
| |
| |-- ShapeList.ts
IShape.ts
大致如下:
export interface IShape {
draw(): void;
}
在
Rectangle.ts
、
Circle.ts
和
Triangle.ts
文件中,我有如下代码:
import { IShape } from './IShape';
export class Circle implements IShape {
static getName: () => 'Circle';
draw(): void {
}
}
然后在
index.ts
中,我会这样做:
import { Circle } from './Circle';
import { Rectangle } from './Rectangle';
import { Triangle } from './Triangle';
export default [
Circle,
Rectangle,
Triangle,
];
最后,在ShapeList.ts
中,我只需利用导出的形状来获得我的形状列表。
从'./shapes'导入形状。
export class ShapeList {
getItems() {
return shapes.map(shape => ({
label: shape.getName(),
action: () => new shape(),
}));
}
}
就是这样。有人可能会认为这仍然是硬编码,因为为形状定义了一个明确的列表,但我会持不同意见,说我们没有硬编码“ShapesForSpecificReasonList”数组,而是利用了我们如何构建形状的有机优势。
现在添加新形状与添加形状的过程相同:
- 编写形状类代码
- 确保它被正确导出