0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Chain of Responsibility デザインパターン

Last updated at Posted at 2021-10-21

チェーンオブレスポンシビリティ

このデザインパターンはGoFのデザインパターンの内の一つである。「誰が何をするか」という責任を鎖のように
繋がれている状態のことです。
例えると、会社の決済のように課長で判断できなかったら部長へ、部長で判断できなかったらその上へ、といったように「誰が決済の判断をするか」ということをどんどん任せていくイメージ。もし誰も行わなかったら何もしない(nilやnullを返す)
メリットとしては誰が処理をするのかを一つに決めないので処理を柔軟に回すことができる。
ただ、責任がどこにあるのかを探索するので処理速度が遅くなるらしい。柔軟性か即効性かで目的別に分ける必要がある。

Swiftではどういう時に使用されるか?

SwiftではUIRespondarオブジェクトが管理している。
ユーザーの操作を
UIButton⇨UIView⇨UIWindow⇨UIApplication(UIViewControllerはUIViewに割り込む形で入っていく。)

//決済を求めるプロトコル
 public protocol RequestSettlement {    
    //決済する関数
    func settlement(request: Any)

    //次の責任者を渡して初期化する
    init(next: RequestSettlement?)

 public class Settlement<T>: RequestSettlement, CustomStringConvertible {

    //自分の次の責任者。nilの場合は、自分自身が最後の責任者となってしまう
    private var nextHandler: RequestSettlement?
       //上のプロパティで宣言したnextHandlerをを初期化
   public  init(next: RequestSettlement?) {
        self.nextHandler = next
    }

    //ジェネリクスで渡した型Tを実際に決済できるか調べて処理する関数
    public func settlement(request: Any) {
        if request is T {
       print("決済したのは\(self)だよ")
        } else {
            //処理が行われずレスポンダーチェインの最後まで到達した場合
            guard let handler = self.nextHandler else {
                print("レスポンダーチェインが終了したよ")
                return
            }
            //次の責任者に送る場合
            print("\(self)では決済できないから,次の責任者である\(handler)に渡すよ")
            handler.settlement(request: request)
        }
    }
0
3
0

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
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?