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