책임의 개념을 갖는 객체들의 체인을 만드는 패턴이다
예를들어 현금, 신용카드, 현금카드 세 개의 결제방법을else if
문으로 만들었다고 해보자
이를 Chain of Responsibility 패턴을 사용한 뒤에 paypal 결제 방법을 추가하여야 한다면 단순히 모듈형식에 체이닝만으로 해결할 수 있다.
import Foundation
protocol Handler {
var nextHandler: Handler? { get set }
func handle(request: [String: Any])
}
extension Handler {
mutating func setNext(handler: Handler) {
self.nextHandler = handler
}
func passToNext(request: [String: Any]) {
if let nextHandler = nextHandler {
nextHandler.handle(request: request)
} else {
print("All handlers failed")
}
}
}
class CashHandler: Handler {
var nextHandler: Handler?
func handle(request: [String: Any]) {
if request["method"] as? String == "cash" {
if let amount = request["amount"] {
print("Processing cash \(amount) won")
}
} else {
print("CashHandler cannot process")
passToNext(request: request)
}
}
}
class CreditCardHandler: Handler {
var nextHandler: Handler?
func handle(request: [String: Any]) {
if request["method"] as? String == "creditCard" {
if let amount = request["amount"] {
print("Processing creditCard \(amount) won")
}
} else {
print("CreditCardHandler cannot process")
passToNext(request: request)
}
}
}
class DebitCardHandler: Handler {
var nextHandler: Handler?
func handle(request: [String: Any]) {
if request["method"] as? String == "debitCard" {
if let amount = request["amount"] {
print("Processing debitCard \(amount) won")
}
} else {
print("DebitCardHandler cannot process")
passToNext(request: request)
}
}
}
var cashHandler = CashHandler()
var creditCardHandler = CreditCardHandler()
let debitCardHandler = DebitCardHandler()
cashHandler.setNext(handler: creditCardHandler)
creditCardHandler.setNext(handler: debitCardHandler)
let payment = [
"method": "paypal",
"amount": 10000
] as [String : Any]
cashHandler.handle(request: payment)
/*
CashHandler cannot process
CreditCardHandler cannot process
DebitCardHandler cannot process
All handlers failed
*/