Help us understand the problem. What is going on with this article?

Swiftでデザインパターン アダプターパターン

More than 1 year has passed since last update.

アダプターパターン

クラスが既にある状態で、それに手を加えずに実装を追加する方法
既存のクラスに手を加えないので、非破壊的な実装ができる

前提事項

  • sayHelloの こんにちは の最後に、 ! を付け足したい要望がきた場合
  • 他の箇所でも使われているため、直接修正はできない
class Person { // 既存のクラス
    func sayHello() -> String {
        return "こんにちは"
    }
}

アダプターパターンを使う(継承バージョン)

protocol ShoutProtocol {
    func shout() -> String
}

class LoudVoicePerson : Person, ShoutProtocol {
    func shout() -> String {
        return super.sayHello() + "!"
    }
}

let loudVoicePerson = LoudVoicePerson()
print(loudVoicePerson.shout())

これでできました。既存のクラスに影響がないため、安全です(リリース間際でも心配しなくてすみます)

ただ、個人的には継承を使うやり方はswiftらしくないと思っており、下記のextensionを使ったほうが好きです。

// extensionを使って、このように実行することも可能

 extension Person : ShoutProtocol {
    func shout() -> String {
        return super.sayHello() + "!"
    }
 }
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away