オブジェクト設計において、定石となる手法をパターン化したものを デザインパターン といいます。
デザインパターンをきちんと勉強していない人でも、Web のおかげで知らず知らずのうちに使って(コピペして)その恩恵を享受しています。
自分自身パターン概要を一読しただけで、あいまいな使い方をしているものが多く、この際勉強を兼ねて GOF 23 パターンのなかでよく利用するものを Swift3 で記述していきたいと思います。
今回は 生成パターン の Prototype について説明します。
目次
- [生成] Prototype パターン
- まとめ
[生成] Prototype パターン
オブジェクトの生成は、通常 クラス から new で オブジェクト を生成しますが、Prototype は、オブジェクト の clone メソッド から オブジェクト の クローン(複製) を生成します。
サンプルコード
Client.swift
[code]
class Client: NSObject {
func createConcretePrototypes() -> [ConcretePrototype] {
let teacher = ConcretePrototype()
var students = [ConcretePrototype]()
// 見本となる教師を教育する
self.educate(student: teacher)
// 教師の能力で1000人の生徒を作る
for _ in 0..<1000 {
let newStudent = teacher.clone() as! ConcretePrototype
students.append(newStudent)
}
return students
}
private func educate(student: ConcretePrototype) {
// 生徒の能力が 100 になるよう教育する
student.ability = 100
}
}
[/code]
ConcretePrototype.swift
[code]
class ConcretePrototype: NSObject, Prototype {
var ability: Int?
func clone() -> AnyObject {
let clonePrototype = ConcretePrototype()
clonePrototype.ability = self.ability
return clonePrototype
}
}
[/code]
ViewController.swift
Prototype は プロトコル により clone メソッドのインタフェースを提供します。
[code]
protocol Prototype {
func clone() -> AnyObject
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// クライアントを生成
let client: Client = Client()
// クライアントの create メソッドを実行
print(client.createConcretePrototypes())
}
}
[/code]
実行結果
[code]
[
・
・
・
[/code]
まとめ
Prototype はその特性上、1つや2つではなく、数十数百〜といったオブジェクトを生成しなければいけない場合に利用します。
次回は 生成パターン の Builder パターンを説明したいと思います。
この記事がみなさんのお役に立ちましたら、下記「Share it」よりブックマークやSNSで共有していただければ幸いです。
