设计思路
- 接口设计:
- 定义
Product
接口,包含商品的基本属性如id
、name
、price
。由于可能存在不同类型商品的特殊属性,部分属性可设为可选。
- 定义
Order
接口,包含订单orderId
以及商品数组products
。
- 类的设计:
- 创建
Product
抽象类实现Product
接口,提供基本的数据验证逻辑,例如价格不能为负数。
- 针对不同类型商品,创建继承自
Product
抽象类的具体商品类,如ElectronicsProduct
,可添加电子产品特有的属性。
- 创建
Order
类实现Order
接口,可在构造函数中对订单数据进行验证,如确保商品数组不为空。
- 性能优化:
- 使用可选属性减少不必要的内存开销,只有在实际需要时才设置这些属性。
- 抽象类用于提取公共逻辑,避免重复代码,提升性能和可维护性。
代码实现
// 商品接口
interface ProductInterface {
id: number;
name: string;
price: number;
description?: string; // 可选属性
}
// 订单接口
interface OrderInterface {
orderId: number;
products: ProductInterface[];
}
// 商品抽象类
abstract class Product implements ProductInterface {
constructor(public id: number, public name: string, public price: number, public description?: string) {
if (price < 0) {
throw new Error('Price cannot be negative');
}
}
}
// 电子产品商品类,继承自Product
class ElectronicsProduct extends Product {
constructor(id: number, name: string, price: number, public warranty: number) {
super(id, name, price);
}
}
// 订单类
class Order implements OrderInterface {
constructor(public orderId: number, public products: ProductInterface[]) {
if (!products || products.length === 0) {
throw new Error('Order must contain at least one product');
}
}
}