1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftでAdapterパターン

Last updated at Posted at 2023-08-02

こちらの記事で記載されている演習内容をSwiftで写経させていただきました。

ざっくりまとめ

  • Adapterパターンの使い道は、インタフェースに互換性のないクラス同士を組み合わせることを目的に使用される
  • 継承や移譲を用いて、Adapteeのメソッドを呼び出す

クラス図

継承パターン

IMG_7EA8B343B4DA-1.jpeg

移譲パターン

IMG_E58587A2CE87-1.jpeg

// Adaptee
class Taro {
    func enjoyWithAllClassmate() {
        print("みんなで楽しむ")
    }
}
// Target interface
protocol Charperson {
    func organizeClass()
}
// 演習1
//class Teacher {
//    func main() {
//        let chairperson: Charperson = NewTaro()
//        chairperson.organizeClass()
//    }
//}

//  継承パターン, Adapter
class NewTaro: Taro, Charperson {
    func organizeClass() {
        enjoyWithAllClassmate()
    }
}

// 移譲パターン, Adapter
class Hanako: Charperson {
    private let taro: Taro
    
    init() {
        self.taro = Taro()
    }
    
    func organizeClass() {
        taro.enjoyWithAllClassmate()
    }
}

// 演習2
class Teacher {
    func main() {
        let chairperson: Charperson = Hanako()
        chairperson.organizeClass()
    }
}


参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?