面试题答案
一键面试abstract class Shape {}
class Circle extends Shape {
drawCircle() {
console.log('Drawing a circle');
}
}
class Rectangle extends Shape {
drawRectangle() {
console.log('Drawing a rectangle');
}
}
class Renderer {
render<T extends Shape>(shape: T) {
if (shape instanceof Circle) {
(shape as Circle).drawCircle();
} else if (shape instanceof Rectangle) {
(shape as Rectangle).drawRectangle();
}
}
}
受限多态在该场景中的作用
- 类型适配:
render
方法使用了泛型T
并约束T
是Shape
的子类型(T extends Shape
)。这使得render
方法能够接收任何Shape
的子类型,实现了对不同具体形状类型的适配。不必为每个具体形状类型都创建单独的渲染方法,增强了代码的灵活性。 - 复用:通过在
Renderer
类中定义一个通用的render
方法,利用受限多态,可以复用该方法来处理所有Shape
子类型的渲染逻辑。同时,通过类型守卫(instanceof
)来判断具体类型,执行相应的特定渲染方法,既保证了代码复用,又保证了类型安全。