LoginSignup
16
15

More than 5 years have passed since last update.

SwiftにおけるBuilderパターンの実装

Last updated at Posted at 2015-04-15

SwiftでDirector無しの簡易的なBuilderパターンを実装してみた。

以下のクラスのビルダーを作成する。

class A {
    var firstName: String?
    var lastName: String?
}

class B: A {
    var middleName: String?
}

ビルダーはBuildableプロトコルを継承することにする。

protocol Buildable {
    typealias BuildType

    func build() -> BuildType
}

BBuilderはABuilderのサブクラスとする。buildをオーバーライドする時に返値の型はBuildTypeの型に変更することが出来た。

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
    }
}

実際にインスタンスを作成するには以下のように行う。

let a = ABuilder()
    .withFirstName("First")
    .withLastName("Last")
    .build()
let b = BBuilder()
    .withFirstName("First")
    .withMiddleName("Middle")
    .withLastName("Last")
    .build()

16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15