6/6 ドメイン駆動設計Chapter13 13-2
13-2 仕様とリポジトリを組み合わせる
プレミアムユーザであることを表す仕様オブジェクト
export class PremiumUserSpecification { isSatisfiedBy(user: User): boolean { return user.getIsPremium(); } }
UserエンティティにisPremiumメソッドが定義されているとする
export class User { constructor( private id: UserId, private name: UserName, private isPremium: boolean, // プレミアムユーザーかどうかを表すプロパティ ) {} // ... getIsPremium(): boolean { // プレミアムユーザーかどうかを返すメソッド return this.isPremium; } }
仕様オブジェクトを使用してリポジトリからエンティティを検索するメソッドを定義
export class UserRepository { // ... findSatisfying(spec: PremiumUserSpecification): User[] { return this.users.filter(user => spec.isSatisfiedBy(user)); } }
リポジトリのメソッドを使用してプレミアムユーザーを検索するサービスを定義
export class UserApplicationService { constructor(private userRepository: UserRepository) {} findPremiumUsers(): User[] { const spec = new PremiumUserSpecification(); return this.userRepository.findSatisfying(spec); } }