Decoratorパターン
2025/5/15 21:38:00
Decoratorパターンで例外のハンドリングができる……ってコト?!
こんな感じっぽい
class ErrorHandlingProductRepositoryDecorator implements IProductRepository {
constructor(private readonly productRepository: IProductRepository) { }
async insert(product: Product) {
try {
this.productRepository.insert(product)
} catch(error) {
// エラーハンドリングの処理
}
}
}
class Application {
constructor(private readonly productRepository: IProductRepository) { }
}
const application = new Application(
new ErrorHandlingProductRepositoryDecorator(
new ProductRepository()
)
)
こうすることで、ProductRepositoryは「エラーハンドリングとか知らね」ってできるし、テストとかでエラーハンドリングしたくない場合はProductRepositoryをApplicationに直接渡してしまえばよいってわけね。