Patterns / Behavioral patterns
image

protocol Strategy {
    func doOperation(_ a: Int, _ b: Int) -> Int
}

//ConcreteStrategy
class AddStrategyStrategy {
    func doOperation(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
}

//ConcreteStrategy
class SubstractStrategyStrategy {
    func doOperation(_ a: Int, _ b: Int) -> Int {
        return a - b
    }
}

//Context
class Calc {
    var strategy: Strategy?

    func execute(_ a: Int, _ b: Int) -> Int {
        if strategy == nil {
            return 0
        }

        return strategy!.doOperation(a, b)
    }

    func setStrategy(_ strategy: Strategy) {
        self.strategy = strategy
    }
}

let calc = Calc()
let result1 = calc.execute(53)
//result1 is 0

calc.setStrategy(AddStrategy())
let result2 = calc.execute(53)
//result2 is 8

calc.setStrategy(SubstractStrategy())
let result3 = calc.execute(53)
//result3 is 2

print("result1 is \(result1)")
print("result2 is \(result2)")
print("result3 is \(result3)")


Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.