LoginSignup
2

More than 5 years have passed since last update.

Swiftで実装するデザインパターン 「Strategy」

Posted at

条件分岐などの戦略部分をクラス化しちゃおうぜ!っていうパターン

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)
    }
}

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