美文网首页
Chain of responsibility

Chain of responsibility

作者: PonyCui | 来源:发表于2015-10-27 15:06 被阅读77次

    在iOS中最常见的责任链模式就是 UIView 的触摸事件传递

    何谓责任链?

    假定一个事件可能被一系列类被处理的时候,如何确保这一事件能有效、有序地被处理?

    //一个简单的例子可以说明这个模式需要解决的问题
    //在面向过程的程序中,我们使用多个 if 判断完成以下这件事情
    import UIKit
    
    let char = "c"
    if char == "c" {
        print("This is c.")
    }
    else if char == "d" {
        print("This is d.")
    }
    else if char == "e" {
        print("This is e.")
    }
    else {
        print("I don't know anything!")
    }
    

    但问题在于,一旦需要添加一个条件的时候,就需要添加一段 else if 的代码块,实际上,这些代码块是冗余的。

    可以使用责任链模式改写上面的程序

    class CharPrinter {
        
        let equalChar: String
        let nextPrinter: CharPrinter?
        
        init(equalChar: String, nextPrinter: CharPrinter?) {
            self.equalChar = equalChar
            self.nextPrinter = nextPrinter
        }
        
        func exec(char: String) {
            if char == equalChar {
                print("This is \(equalChar)")
            }
            else if let nextPrinter = self.nextPrinter {
                nextPrinter.exec(char)
            }
            else {
                print("I don't know anything!")
            }
        }
        
    }
    
    let chainPrinter = CharPrinter(equalChar: "c",
        nextPrinter: CharPrinter(equalChar: "d",
            nextPrinter: CharPrinter(equalChar: "e",
                nextPrinter: nil)))
    
    chainPrinter.exec("c")
    

    参考文章

    http://openhome.cc/Gossip/DesignPattern/ChainofResponsibility.htm

    相关文章

      网友评论

          本文标题:Chain of responsibility

          本文链接:https://www.haomeiwen.com/subject/hfmxhttx.html