Created
May 20, 2022 13:51
-
-
Save rinotc/37dc90e5f937e2374481f1a356587679 to your computer and use it in GitHub Desktop.
This file contains 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
class Person private (val firstName: String, val lastName: String, val age: Int) | |
object Person { | |
class Builder { | |
var firstName: String = "" | |
var lastName: String = "" | |
var age: Int = 0 | |
private var hasFirstName: Boolean = false | |
private var hasLastName: Boolean = false | |
def setFirstName(firstName: String): Builder = { | |
this.firstName = firstName | |
this.hasFirstName = true | |
this | |
} | |
def setLastName(lastName: String): Builder = { | |
if (!hasFirstName) { | |
throw new IllegalStateException("先にfirstNameをセットしなければならない") | |
} | |
this.lastName = lastName | |
this.hasLastName = true | |
this | |
} | |
def setAge(age: Int): Builder = { | |
this.age = age | |
this | |
} | |
def build: Person = { | |
if (!hasLastName) { | |
throw new IllegalStateException("先にlastNameをセットしなければならない") | |
} | |
new Person(firstName, lastName, age) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
下記の type-safe builder パターンをクラスの内部状態で表現するこのようになる。
type-safe builderでは、型パラメータによって呼び出し状態を判定していたが、これはこのように呼び出したかどうかをもつフラグを持ち、そのフラグ状態によって事前条件違反をとして例外を投げる実装になる。
この場合は判定が実行時になる。
https://gist.github.com/rinotc/3e56f67a7ee938f4744025733ce1923c#file-typesafebuildersample-scala