Created
August 12, 2022 04:54
-
-
Save harajune/8512bfc53a8142c205b5996c2309f5e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // マーカーインターフェース | |
| interface Money { | |
| getValue(): number | |
| } | |
| class Dollar implements Money { | |
| constructor(private readonly value: number) {} | |
| getValue() { | |
| return this.value | |
| } | |
| // 最初から引数 other の型を Dollar とすれば条件分岐は不要 | |
| // だが、説明のためにあえて広い Money 型にしている | |
| equals(other: Money) { | |
| if (other instanceof Dollar) { | |
| throw new Error('Variable other is not Dollar.') | |
| } | |
| return this.value === other.getValue() | |
| } | |
| } | |
| class Yen implements Money { | |
| constructor(private readonly value: number) {} | |
| getValue() { | |
| return this.value | |
| } | |
| // 最初から引数 other の型を Dollar とすれば条件分岐は不要 | |
| // だが、説明のためにあえて広い Money 型にしている | |
| equals(other: Money) { | |
| if (other instanceof Yen) { | |
| throw new Error('Variable other is not Dollar.') | |
| } | |
| return this.value === other.getValue() | |
| } | |
| } | |
| class Transaction { | |
| constructor( | |
| private readonly a: Dollar, | |
| private readonly b: Dollar | |
| ) {} | |
| add() { | |
| const sum = this.a.getValue() + this.b.getValue() | |
| return new Dollar(sum) | |
| } | |
| } | |
| // Value Object | |
| const dollar = new Dollar(100) | |
| const yen = new Yen(100) | |
| // 型エラーになる | |
| new Transaction(dollar, yen) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment