Last active
August 29, 2015 14:19
-
-
Save rizumita/20ee63875222f62b48af to your computer and use it in GitHub Desktop.
SwiftにおけるBuilderパターンの実装 ref: http://qiita.com/rizumita/items/fe90d09a07d9b2d0e490
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 A { | |
var firstName: String? | |
var lastName: String? | |
} | |
class B: A { | |
var middleName: String? | |
} |
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
protocol Buildable { | |
typealias BuildType | |
func build() -> BuildType | |
} |
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 ABuilder: Buildable { | |
typealias BuildType = A | |
private var firstName: String? | |
private var lastName: String? | |
func withFirstName(name: String) -> Self { | |
firstName = name | |
return self | |
} | |
func withLastName(name: String) -> Self { | |
lastName = name | |
return self | |
} | |
func build() -> A { | |
let result = A() | |
result.firstName = firstName | |
result.lastName = lastName | |
return result | |
} | |
} | |
class BBuilder: ABuilder { | |
typealias BuildType = B | |
private var middleName: String? | |
func withMiddleName(name: String) -> Self { | |
self.middleName = name | |
return self | |
} | |
override func build() -> B { | |
let result = B() | |
result.firstName = firstName | |
result.middleName = middleName | |
result.lastName = lastName | |
return result | |
} | |
} |
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
let a = ABuilder() | |
.withFirstName("First") | |
.withLastName("Last") | |
.build() | |
let b = BBuilder() | |
.withFirstName("First") | |
.withMiddleName("Middle") | |
.withLastName("Last") | |
.build() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment