面试题答案
一键面试场景描述
在一个电商产品列表页面中,需要渲染不同类型的产品卡片组件,如普通商品卡片、促销商品卡片和新品卡片。这些卡片有一些共同的属性和方法,但也有各自独特的部分。
利用TypeScript多态特性优化
- 定义基类:
// 定义产品卡片基类
class ProductCard {
constructor(public title: string, public price: number) {}
// 基类方法,用于显示基本信息
displayBasicInfo(): void {
console.log(`Title: ${this.title}, Price: ${this.price}`);
}
}
这里定义了一个ProductCard
基类,包含title
和price
属性,以及一个显示基本信息的方法displayBasicInfo
。这是所有产品卡片的共性部分。
- 定义子类:
// 普通商品卡片子类
class NormalProductCard extends ProductCard {
constructor(title: string, price: number) {
super(title, price);
}
// 可以重写基类方法或添加新方法
displayFullInfo(): void {
super.displayBasicInfo();
console.log('This is a normal product.');
}
}
// 促销商品卡片子类
class PromotionProductCard extends ProductCard {
constructor(title: string, price: number, public discount: number) {
super(title, price);
}
// 重写显示基本信息方法以包含折扣信息
displayBasicInfo(): void {
console.log(`Title: ${this.title}, Price: ${this.price}, Discount: ${this.discount}%`);
}
}
// 新品卡片子类
class NewProductCard extends ProductCard {
constructor(title: string, price: number) {
super(title, price);
}
// 新方法表示新品特性
showNewMark(): void {
console.log('This is a new product!');
}
}
每个子类继承自ProductCard
基类,既拥有基类的属性和方法,又可以根据自身特点重写方法或添加新方法。例如PromotionProductCard
重写了displayBasicInfo
方法以显示折扣信息。
- 多态使用:
// 定义一个函数来展示产品卡片信息
function displayProductCard(card: ProductCard) {
card.displayBasicInfo();
if (card instanceof NormalProductCard) {
card.displayFullInfo();
} else if (card instanceof PromotionProductCard) {
// 可以处理促销商品特有的逻辑
} else if (card instanceof NewProductCard) {
(card as NewProductCard).showNewMark();
}
}
// 创建不同类型的产品卡片实例
const normalCard = new NormalProductCard('Normal Product', 100);
const promotionCard = new PromotionProductCard('Promotion Product', 200, 10);
const newCard = new NewProductCard('New Product', 150);
// 调用函数展示卡片信息
displayProductCard(normalCard);
displayProductCard(promotionCard);
displayProductCard(newCard);
displayProductCard
函数接受一个ProductCard
类型的参数,由于多态特性,它可以处理任何子类的实例。根据实际传入的子类实例,函数可以执行相应的方法,这样在渲染产品卡片组件时,代码结构更加清晰,可维护性更高。当需要添加新的产品卡片类型时,只需要定义新的子类并遵循基类的接口,而不需要大幅修改现有的展示逻辑。