条件分岐などの戦略部分をクラス化しちゃおうぜ!っていうパターン
strategy.swift
//: Playground - noun: a place where people can play
import UIKit
struct Human {
let age: Int
let height: Int
let weight: Int
}
// Strategy
protocol Comparator {
func compare(h1: Human, h2: Human) -> Int
}
// ConcreteStrategy
struct AgeComparator: Comparator {
func compare(h1: Human, h2: Human) -> Int {
if h1.age > h2.age {
return 1
} else if h1.age == h2.age {
return 0
} else {
return -1
}
}
}
// ConcreteStrategy2
struct HeightComparator: Comparator {
func compare(h1: Human, h2: Human) -> Int {
if h1.height > h2.height {
return 1
} else if h1.weight == h2.weight {
return 0
} else {
return -1
}
}
}
struct WeightComparator: Comparator {
func compare(h1: Human, h2: Human) -> Int {
if h1.weight > h2.weight {
return 1
} else if h1.weight == h2.weight {
return 0
} else {
return -1
}
}
}
struct MyClass {
let comparator: Comparator
func compare(h1: Human, h2: Human) -> Int {
return comparator.compare(h1: h1, h2: h2)
}
}