返回

洞悉TypeScript:抽象方法和抽象类的设计精髓

前端

TypeScript作为一种前端语言,其形式更类似于后端Java语言。相对于JavaScript而言,TypeScript更体现出面向对象的编程方式,其提供的参数校验、接口、泛型等特性,使其在开发大型前端项目时有着出色的表现。因此,作为一名前端开发人员,掌握TypeScript语言是非常必要的。

TypeScript中的类、多态、抽象方法和抽象类是面向对象编程的核心概念。理解和掌握这些概念对于构建复杂的应用程序至关重要。

类是用来具有相同属性和行为的对象的蓝图。类中的属性定义了对象的属性,而类中的方法定义了对象的行为。

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  speak() {
    console.log(`My name is ${this.name} and I am ${this.age} years old.`);
  }
}

多态

多态是指具有相同父类或接口的对象可以具有不同的行为。这意味着我们可以使用同一个方法来调用具有不同子类或实现的对象,而无需担心具体对象类型。

class Employee extends Person {
  salary: number;

  constructor(name: string, age: number, salary: number) {
    super(name, age);
    this.salary = salary;
  }

  work() {
    console.log(`I am working.`);
  }
}

class Manager extends Employee {
  bonus: number;

  constructor(name: string, age: number, salary: number, bonus: number) {
    super(name, age, salary);
    this.bonus = bonus;
  }

  work() {
    console.log(`I am managing.`);
  }
}

const person = new Person("John", 30);
const employee = new Employee("Jane", 25, 1000);
const manager = new Manager("Mary", 40, 2000, 500);

person.speak();
employee.speak();
manager.speak();

person.work();
employee.work();
manager.work();

抽象方法和抽象类

抽象方法是只声明不实现的方法。抽象类是包含至少一个抽象方法的类。抽象类不能被实例化,但可以被继承。

abstract class Shape {
  abstract area(): number;
}

class Circle extends Shape {
  radius: number;

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

  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

class Rectangle extends Shape {
  width: number;
  height: number;

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

  area(): number {
    return this.width * this.height;
  }
}

const circle = new Circle(5);
const rectangle = new Rectangle(10, 20);

console.log(circle.area());
console.log(rectangle.area());

抽象方法和抽象类是一种很好的方法,可以确保代码的可扩展性和可维护性。它们可以帮助我们创建更灵活和更可重用的代码。