// 定义一个接口,用于规范图形的公共属性
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
。子类(如 Circle
和 Rectangle
)继承自 Shape
抽象类,从而可以复用这些公共的属性和方法,避免重复代码。
- 抽象方法定义:
Shape
抽象类定义了抽象方法 draw
,强制要求子类必须实现该方法来绘制各自特定的图形,保证了不同图形绘制方法的一致性,同时也给子类留下了实现细节的灵活性。