Chapter 22: Chain of Responsibility

大綱

When should you use it?

  • The chain-of-responsibility pattern is a behavioral design pattern that allows an event to be processed by one of many handlers.

  • The client : accepts and passes events to an instance of a handler protocol.

    • Events : may be simple, property-only structs or complex objects, such as intricate user actions.

  • The handler protocol : defines required properties and methods that concrete handlers must implemen.

  • The first concrete handler : implements the handler protocol, and it’s stored directly by the client. Upon receiving an event, it first attempts to handle it. If it’s not able to do so, it passes the event on to its next handler.

    • 将这些处理者组成责任链,在当前处理者无法处理或不符合当前条件时,将请求传递给下一个处理者.

    • When should you use it?

      • Use this pattern whenever you have a group of related objects that handle similar events but vary based on event type, attributes or anything else related to the event.

Playground example

  • 目標 : 構建一個硬幣製造機

  • Step1: 先構建所需要的model

  • Step2: 建立handler protocol

  • Step3: 建立handler class

  • Step4: 實作CoinHandlerProtocol

  • Step5: 建立Client

What should you be careful about?

  • The chain-of-responsibility pattern works best for handlers that can determine very quickly whether or not to handle an event.

    • Be careful about creating one or more handlers that are slow to pass an event to the next handler.

    • 因为需要在责任链上传递责任,直到找到合适的对象来处理,所以可能会导致处理的延迟。因此在延迟不允许过高的场景下不适合使用责任链模式。

    • What happens if an event can’t be handled. What if you return nil, throw an error or something else? You should identify this upfront, so you can plan your system appropriately.

    • Consider whether or not an event needs to be processed by more than one handler. As a variation on this pattern, you can forward the same event to all handlers, instead of stopping at the first one that can handle it, and return an array of response objects.

Tutorial project

  • 目標: RWSecret App

    • Task will be to set up a handler chain to perform decryption.

Key points

  • The chain-of-responsibility pattern allows an event to be processed by one of many handlers. It involves three types: a client, handler protocol, and concrete handlers.

    • The client accepts events and passes them onto its handler protocol instance;

    • the handler protocol defines required methods and properties each concrete handler much implement

    • each concrete handler can accept an event and in turn either handle it or pass it onto the next handler.

  • This pattern thereby defines a group of related handlers, which vary based on the type of event each can handle. If you need to handle new types of events, you simply create a new concrete handler.

Last updated