设计模式-18.桥接模式

122 阅读1分钟

一句话总结

将抽象部分和实现部门分离,是它们都能独立的变化。这里的抽象部分实现部门指的不是抽象类实现类,用电脑例子讲,抽象部分是操作系统、软件,实现部分是硬件。

Code

protocol Implementor {
    func operation()
}

class ConcreteImplementorA: Implementor {
    func operation() {
        print("具体实现A的方法执行")
    }
}

class ConcreteImplementorB: Implementor {
    func operation() {
        print("具体实现B的方法执行")
    }
}

class Abstraction {
    var implementor: Implementor = ConcreteImplementorA()
    
    func operation() {
        implementor.operation()
    }
}

class RefinedAbstraction: Abstraction {
    override func operation() {
        implementor.operation()
    }
}

func main() {
    let cb = RefinedAbstraction()
    
    cb.implementor = ConcreteImplementorA()
    cb.operation()
    
    cb.implementor = ConcreteImplementorB()
    cb.operation()
}

何时使用?

如果要实现的系统有多角度分类,每一种分类都有可能变化,那么就应该将每一角度分离出来,让它们独立变化。