LoginSignup
0
0

More than 5 years have passed since last update.

TECHSCOREのFlyweight パターンをSwiftでかく

Posted at

はじめに

こちらのページで紹介されているFlyweight パターンをSwiftで書いてみたときのメモ
http://www.techscore.com/tech/DesignPattern/Flyweight.html/


class HumanLetterFactory {

    var dic = [String: Target]()

    static let singleton = HumanLetterFactory()

    func printHumanLetter() {
        for (key, value) in dic {
            print("dictionary key is \(key), value is \(value)")
        }
    }


    func getHumanLetter(letter: String) -> Target {
        var humanLetter = dic[letter]
        if humanLetter == nil {
            humanLetter = Target(str: letter)
            dic[letter] = humanLetter
        }
        return humanLetter!
    }


}

class Target {
    let str: String

    init(str: String) {
        self.str = str
    }

    func output() {
        print(str)
    }
}
let test = HumanLetterFactory.singleton
test.getHumanLetter(letter: "あ").output()
test.getHumanLetter(letter: "い").output()
test.getHumanLetter(letter: "あ").output()
test.getHumanLetter(letter: "う").output()
test.printHumanLetter()

//シングルトンパターンを使っているから辞書に入っている値を取り出すと、前に作ったインスタンスに入れた値が出てくる
let test2 = HumanLetterFactory.singleton

test2.printHumanLetter()

実行結果

あ
い
あ
う
dictionary key is あ, value is Main.Target
dictionary key is い, value is Main.Target
dictionary key is う, value is Main.Target
dictionary key is あ, value is Main.Target
dictionary key is い, value is Main.Target
dictionary key is う, value is Main.Target

参考文献

Swiftで学ぶデザインパターン20 (Flyweightパターン)

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