架构设计基础

桥接模式

2019-03-23  本文已影响0人  架构师的一小步

桥接模式定义

桥接模式解决问题

桥接模式使用场景

桥接模式角色划分

\color{red}{四个核心角色}

桥接模式原理案例

喝咖啡?
型号:大、中、小杯
配料:加冰、不加冰、加糖、不加糖

//
//  CoffeeAddtives.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//抽象部分:咖啡添加剂
class CoffeeAddtives: NSObject {

    //业务逻辑
    func addtives() -> String {
        return ""
    }
    
}

//
//  IceAddtives.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//加冰
class IceAddtives: CoffeeAddtives {

    override func addtives() -> String {
        return "加冰"
    }
    
}

//
//  NonIceAddtives.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//不加冰
class NonIceAddtives: CoffeeAddtives {

    override func addtives() -> String {
        return "不加冰"
    }
    
}

//
//  SugarAddtives.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//加糖
class SugarAddtives: CoffeeAddtives {

    override func addtives() -> String {
        return "加糖"
    }
    
}

//
//  NonSugarAddtives.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//不加糖
class NonSugarAddtives: CoffeeAddtives {

    override func addtives() -> String {
        return "不加糖"
    }
    
}

//
//  Coffee.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//抽象实现部分:型号
class Coffee: NSObject {
    //第一个维度
    var addtives:CoffeeAddtives
    //第二个维度
    //第三个维度
    
    init(addtives:CoffeeAddtives) {
        self.addtives = addtives
    }
    
    func makeCoffee() {
        
    }
    
}

//
//  BigCoffee.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

class BigCoffee: Coffee {

    override func makeCoffee() {
        print("大杯\(addtives.addtives())的咖啡")
    }
    
}

//
//  MediumCoffee.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

class MediumCoffee: Coffee {

    override func makeCoffee() {
        print("中杯\(addtives.addtives())的咖啡")
    }
    
}

//
//  SmallCoffee.swift
//  Dream_20180723_Bridge
//
//  Created by Dream on 2018/7/23.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

class SmallCoffee: Coffee {

    override func makeCoffee() {
        print("小杯\(addtives.addtives())的咖啡")
    }
    
}

调用

        //来一杯饮料
        let ice = SugarAddtives()
        let coffee = BigCoffee(addtives: ice)
        coffee.makeCoffee()

输出

大杯加糖的咖啡

桥接模式UML

上一篇下一篇

猜你喜欢

热点阅读