Proxy(代理)

Protection Proxy

/*:

### Example
*/
protocol DoorOperator {
    func open(doors: String) -> String
}

class HAL9000 : DoorOperator {
    func open(doors: String) -> String {
        return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
    }
}

class CurrentComputer : DoorOperator {
    private var computer: HAL9000!

    func authenticate(password: String) -> Bool {

        guard password == "pass" else {
            return false;
        }

        computer = HAL9000()

        return true
    }

    func open(doors: String) -> String {

        guard computer != nil else {
            return "Access Denied. I'm afraid I can't do that."
        }

        return computer.open(doors: doors)
    }
}
/*:
### Usage
*/
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"

computer.open(doors: podBay)

computer.authenticate(password: "pass")
computer.open(doors: podBay)

Virtual Proxy

/*:

### Example
*/

protocol HEVSuitMedicalAid {
    func administerMorphine() -> String
}

class HEVSuit : HEVSuitMedicalAid {
    func administerMorphine() -> String {
        return "Morphine administered."
    }
}

class HEVSuitHumanInterface : HEVSuitMedicalAid {
    lazy private var physicalSuit: HEVSuit = HEVSuit()

    func administerMorphine() -> String {
        return physicalSuit.administerMorphine()
    }
}
/*:
### Usage
*/
let humanInterface = HEVSuitHumanInterface()
humanInterface.administerMorphine()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 动机 有时,我们需要对一个对象的访问进行控制。比如说如果我们有一些开销较大的对象,但是只需要使用其中一部分方法,我...
    holysu阅读 1,034评论 0 5
  • 原文收录在我的 GitHub博客 (https://github.com/jawil/blog) ,喜欢的可以关注...
    微醺岁月阅读 2,401评论 0 20
  • 摘要 本篇笔记针对Java设计模式中最难理解的代理者模式进行讲解,从静态代理、动态代理,及Java相关代理类的应用...
    木木彬阅读 569评论 1 4
  • 假如回到17岁: 1.我会认真对待不喜欢的老师,与不喜欢的人相处更能锻炼自己 2.选择是有代价的。我填报志愿一定不...
    谢小仙阅读 183评论 0 0
  • 茵茵草地 你跑着跳着 欢脱地追着泡泡 我看在眼里 刻在心里 我的宝贝 你是我祈福最好的回应 你爽朗的笑声 治愈我所...
    曦城365阅读 246评论 0 2