はじめに
こちらのページで紹介されている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