// 定义Shape接口
interface Shape {
draw(): void;
}
// Circle类实现Shape接口
class Circle implements Shape {
draw(): void {
console.log('绘制圆形');
}
}
// Rectangle类实现Shape接口
class Rectangle implements Shape {
draw(): void {
console.log('绘制矩形');
}
}
// 多态性展示
function drawShapes(shapes: Shape[]) {
shapes.forEach(shape => {
shape.draw();
});
}
// 创建Shape数组并添加Circle和Rectangle实例
const shapes: Shape[] = [new Circle(), new Rectangle()];
// 调用drawShapes函数
drawShapes(shapes);
多态性解释
- 多态的体现:在上述代码中,
drawShapes
函数接收一个Shape
类型的数组。虽然数组中实际存储的是Circle
和Rectangle
类的实例,但由于这两个类都实现了Shape
接口,它们都拥有draw
方法。当drawShapes
函数遍历这个数组并调用每个元素的draw
方法时,会根据实际对象的类型(Circle
或Rectangle
)调用对应的draw
方法实现。
- 好处:这种方式提高了代码的可维护性和扩展性。如果后续添加新的实现了
Shape
接口的类(比如Triangle
),只需要创建新类并实现draw
方法,然后将其添加到Shape
数组中,drawShapes
函数无需修改即可正确处理新类型的对象。实现了不同对象以统一方式进行操作,符合多态的概念。