MST

星途 面试题库

面试题:TypeScript 中接口与抽象类结合在简单项目架构中的应用

假设你正在开发一个简单的图形绘制库,有圆形、矩形等图形。请使用 TypeScript 的接口与抽象类结合的方式,设计一个基本的架构,包含图形的公共属性和方法,以及不同图形特有的绘制方法。并解释接口和抽象类分别在这个架构中起到了什么作用。
15.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义一个接口,用于规范图形的公共属性
interface ShapeProperties {
    color: string;
}

// 定义抽象类,包含图形的公共方法和部分实现
abstract class Shape implements ShapeProperties {
    color: string;

    constructor(color: string) {
        this.color = color;
    }

    // 抽象方法,由具体图形类实现
    abstract draw(): void;

    // 公共方法
    setColor(newColor: string): void {
        this.color = newColor;
    }
}

// 圆形类继承自抽象类 Shape
class Circle extends Shape {
    radius: number;

    constructor(color: string, radius: number) {
        super(color);
        this.radius = radius;
    }

    draw(): void {
        console.log(`绘制一个颜色为 ${this.color},半径为 ${this.radius} 的圆形`);
    }
}

// 矩形类继承自抽象类 Shape
class Rectangle extends Shape {
    width: number;
    height: number;

    constructor(color: string, width: number, height: number) {
        super(color);
        this.width = width;
        this.height = height;
    }

    draw(): void {
        console.log(`绘制一个颜色为 ${this.color},宽为 ${this.width},高为 ${this.height} 的矩形`);
    }
}

接口的作用

  • 属性规范ShapeProperties 接口定义了图形都应该具有的 color 属性,这样任何实现该接口的类都必须包含 color 属性,从而保证了不同图形类在属性上的一致性,实现了一种契约式的编程。

抽象类的作用

  • 代码复用Shape 抽象类实现了 ShapeProperties 接口,并包含了公共属性 color 和公共方法 setColor。子类(如 CircleRectangle)继承自 Shape 抽象类,从而可以复用这些公共的属性和方法,避免重复代码。
  • 抽象方法定义Shape 抽象类定义了抽象方法 draw,强制要求子类必须实现该方法来绘制各自特定的图形,保证了不同图形绘制方法的一致性,同时也给子类留下了实现细节的灵活性。