设计思路
- 依赖注入:使用TypeScript装饰器实现依赖注入,通过装饰器将
InventoryService
和ShippingService
注入到ProductService
中。
- 异步处理:由于
InventoryService
和ShippingService
的调用是异步的,使用async/await
来处理异步操作,确保代码的可读性和顺序性。
- 竞争条件处理:利用
Promise.all
来并行执行异步操作,避免竞争条件。同时,可以使用锁机制或队列来进一步处理复杂的并发情况。
- 异步中间件:通过装饰器实现异步中间件功能,在服务调用前后执行一些通用的逻辑,如日志记录、性能监控等。
代码示例
// 定义服务接口
interface InventoryService {
checkInventory(productId: string): Promise<boolean>;
}
interface ShippingService {
calculateShipping(productId: string): Promise<number>;
}
// 实现服务
class DefaultInventoryService implements InventoryService {
async checkInventory(productId: string): Promise<boolean> {
// 模拟异步操作
await new Promise(resolve => setTimeout(resolve, 1000));
return true;
}
}
class DefaultShippingService implements ShippingService {
async calculateShipping(productId: string): Promise<number> {
// 模拟异步操作
await new Promise(resolve => setTimeout(resolve, 1000));
return 10;
}
}
// 依赖注入装饰器
function inject<T>(service: T) {
return function (target: any, propertyKey: string) {
target[propertyKey] = service;
};
}
// 异步中间件装饰器
function asyncMiddleware(middleware: (target: any, ...args: any[]) => Promise<void>) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
await middleware(this, ...args);
return originalMethod.apply(this, args);
};
return descriptor;
};
}
// 产品服务
class ProductService {
@inject(new DefaultInventoryService())
private inventoryService: InventoryService;
@inject(new DefaultShippingService())
private shippingService: ShippingService;
@asyncMiddleware(async function (this: ProductService, productId: string) {
console.log(`Starting processing for product ${productId}`);
})
async processProduct(productId: string) {
const [hasInventory, shippingCost] = await Promise.all([
this.inventoryService.checkInventory(productId),
this.shippingService.calculateShipping(productId)
]);
if (hasInventory) {
console.log(`Product ${productId} is available. Shipping cost: ${shippingCost}`);
} else {
console.log(`Product ${productId} is out of stock.`);
}
}
}
// 测试
const productService = new ProductService();
productService.processProduct('12345');
代码解释
- 服务接口和实现:定义了
InventoryService
和ShippingService
接口及其实现类,模拟了异步操作。
- 依赖注入装饰器:
inject
装饰器将服务实例注入到ProductService
的属性中。
- 异步中间件装饰器:
asyncMiddleware
装饰器在processProduct
方法调用前后执行中间件逻辑。
- 产品服务:
ProductService
类使用依赖注入装饰器注入InventoryService
和ShippingService
,并使用asyncMiddleware
装饰器添加异步中间件。processProduct
方法使用Promise.all
并行执行异步操作,并处理结果。
- 测试:创建
ProductService
实例并调用processProduct
方法,观察输出结果。