Before talking about the interview must ask the event distribution, that some students said, it is not easy to understand, if you happen to meet the interviewer who does not ask? Don’t worry, there’s a trick. We know that the dispatchTouchEvent recursion is actually a typical chain of responsibility model, so when the interviewer asks you which design patterns you have used or are familiar with, you can say chain of responsibility model. Well, that’s where it leads us.

Chain of Responsibility model

A Chain of Responsibility Pattern, as its name implies, is an execution Chain used to handle relevant transaction responsibilities. Each node in the Chain has the opportunity (conditional matching) to process requested transactions. If a node has finished processing, it can be passed to the next node to continue processing or return to the end of processing according to actual service requirements.

Usage scenarios

  • Multiple objects can handle the same request, and which object to handle is determined dynamically at run time. For example: to find a partner (request), one blind date after another (the blind date is the handler), you can complete the request if both sides feel suitable, of course, it is possible that all the blind date does not like you (hard to break down).
  • You need to dynamically specify a set of objects to handle requests. Again for example: find the object to get married (request), need a lot of people (processing) agree, the father-in-law check the character image good agreed, mother-in-law check have a house have a car agreed,For God’s sake, check the figure of eight. YesCivil affairs bureau check both unmarried agreed to request success. One of these interrupts failed the request.

I am such a parable devil. This kind of chain structure, each node can be disassembled and connected again, can be very convenient to adjust the number of nodes, priority and so on.

UML class diagrams

  • Handler: Abstract Handler that declares a method to process a request and holds a reference to the next Handler in it
  • ConcreteHandler: ConcreteHandler that processes a request and forwards it to the next handler if it cannot handle it
  • The request is simplified into an int, which can encapsulate the request abstract class and extend it to different request types in real scenarios.

shut up and show me the code

The aforementioned genius metaphor is too complex to write in code. Let’s go back to the case of leave. The sample code uses Kotlin, which can be understood by those who have not learned Kotlin.

A note is a request for:

data class Request(
        val leaveDay: Float.// Duration of absence
        val msg: String // The reason for the leave
)
Copy the code

The leaders are the handlers:

open class Handler(
        val name: String, // Handler name
        val leaveLimit: Float // The maximum time for approval) {var next: Handler? = null

    open fun handRequest(request: Request) {
        if (request.leaveDay <= leaveLimit) {
            println("${request.msg}- > take time off,$nameMust have the")}else {
            println("$name: more than${leaveLimit}God, let the leader handle it.") next? .handRequest(request) } } }// The Handler can be extended as required
class FinalHandler(name: String) : Handler(name, Float.MAX_VALUE) {
    override fun handRequest(request: Request) {
        println("$name:${request.msg}> < p style = "max-width: 100%; clear: both;)}}Copy the code

The handler then forms a chain of responsibilities and starts sending requests to the first node

fun main(a) {
    val leader = Handler("Immediate superior".1f)
    val manager = Handler("Manager".30f)
    val generalManager = Handler("General manager".365f)
    val boss = FinalHandler("The boss")

    / / group chain
    leader.next = manager
    manager.next = generalManager
    generalManager.next = boss

    leader.handRequest(Request(1f, "Headache and fever.")) // Brain fever is isolated for observation
    println("-- -- -- -- -- -- -- -- -- -- -- -- --")
    leader.handRequest(Request(14f, "Wife gives birth to baby."))
    println("-- -- -- -- -- -- -- -- -- -- -- -- --")
    leader.handRequest(Request(365f, "How big is the world? I want to see it."))
    println("-- -- -- -- -- -- -- -- -- -- -- -- --")
    leader.handRequest(Request(3650f, "Don't want to go to work"))}Copy the code

Done, run the results:

Headaches brain hot - > leave, the immediate superior must -- -- -- -- -- -- -- -- -- -- -- -- -- immediate superior: more than 1.0 days, let the leadership to deal with Wife gave birth to baby - > ask for leave, the manager must -- -- -- -- -- -- -- -- -- -- -- -- -- immediate superior: more than 1.0 days, let leadership processing manager: More than 30.0 days, let the leadership deal with the world hot? Big, I want to see -> leave, the general manager approved ------------- direct superior: more than 1.0 days, let the leadership deal with the manager: more than 30.0 days, let the leadership deal with the general manager: more than 365.0 days, let the leadership deal with the boss: Don't want to go to work -> look for finance to get next salary, need not come!Copy the code

Through the chain of responsibility, each level can do its part by processing the request and passing it on to the next node if it can’t. There is no limit to the number of nodes in this chain, even if you have more leaders do not have to be afraid of it, anyway, to ask for leave from the direct superior, the leave note will be passed up level by level.

Furthermore, if not leave, is reimbursed? You can extend the Request class Request. The chain is the same chain but can handle different requests. Isn’t that flexible?

conclusion

The world is not perfect, and neither is the chain of responsibility model.

The advantages are obvious: you can decouple requests and handlers, increasing code flexibility.

Disadvantages: Too much traversal processing may affect performance; Debugging trouble needs to be looked at at every level.

Okay, chain of responsibility, remember to tell your interviewer that event distribution is a chain of responsibility, layer by layer, find the View that can consume it.

Welcome to pay attention to the “Android interviewer” in the public account background message exchange your favorite design mode