2
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でTemplate Methodパターン

Last updated at Posted at 2023-08-02

Java言語で学ぶデザインパターン入門第3版 の「第3章 Templete Method - 具体的な処理をサブクラスにまかせる」に記載されているソースコードを参考にさせていただき、Swiftで書いてみました。

ざっくりまとめ

  • 共通的な処理をスーパークラスに定義し、それぞれのサブクラスで具体的な処理を実装する
  • iOSのアプリ開発でいうところの同じようなViewControllerがあるとしたら、BaseViewControllerを定義し、それぞれのViewControllerが継承するみたいな感じ。
class AbstractDisplay {
    func open() {
    }
    
    func print() {
    }
    
    func close() {
    }
    
    func display() {
        open()
        for i in 1 ... 5 {
            print()
        }
        close()
    }
}

class CharDisplay: AbstractDisplay {
    private let char: Character
    init(char: Character) {
        self.char = char 
    }
    
    override func open() {
        Swift.print("<<", terminator: "")
    }
    
    override func print() {
        Swift.print(char, terminator: "")
    }
    
    override func close() {
        Swift.print(">>")
    }
}

class StringDisplay: AbstractDisplay {
    private let string: String
    private let width: Int
    
    init(string: String) {
        self.string = string
        self.width = string.count
    }
    
    override func open() {
        printLine()
    }
    
    override func print() {
        Swift.print("|\(string)|")
    }
    
    override func close() {
        printLine()
    }
    
    func printLine() {
        Swift.print("+", terminator: "")
        for i in 1 ... width {
            Swift.print("-", terminator: "")
        }
        Swift.print("+")
    }
}

let d1 = CharDisplay(char: "H")
let d2 = StringDisplay(string: "Hello, world.")

d1.display()
d2.display()

/* 実行結果
<<HHHHH>>
+-------------+
|Hello, world.|
|Hello, world.|
|Hello, world.|
|Hello, world.|
|Hello, world.|
+-------------+
*/

参考文献

  • 結城 浩.『Java言語で学ぶデザインパターン入門第3版』.SBクリエイティブ、2021
2
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
2
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?