swift Swift中桥接模式的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift中桥接模式的示例相关的知识,希望对你有一定的参考价值。

//Bridge pattern (Structural)
//Decouples an abstraction from its implementation, so that the two can vary independently.
// Accomplished by seperating two interacting features and then creating a bridge type to
// handle where they overlap
protocol Database {
    func closeConnection()
    func openConnection()
    func saveRecord(recordToSave: Record)
}

protocol Record {
    var savedToDb: Bool { get set }
    
    func printRecord()
    mutating func updateAsSavedToDb()
    func verifyRecord() -> Record
}

struct SqlDb: Database {
    func closeConnection() {
        print("Closing Connection...")
    }
    
    func openConnection() {
        print("Opening Connection...")
    }
    
    func saveRecord(recordToSave: Record) {
        print("Saving Record...")
    }
}

struct BasicRecord: Record {
    var savedToDb: Bool
    
    func printRecord() {
        print("Printing Record...")
    }
    
    mutating func updateAsSavedToDb() {
        savedToDb = true
    }
    
    func verifyRecord() -> Record {
        print("Verifying Record...")
        return self
    }
}

/* 
 Databases and Records can now very independantly of each other
 If the logic to save a record needs to be updated it only has to be updated in one place
 */
struct RecordBridge {
    static func saveRecord(recordToSave record: Record, database: Database) -> Record {
        var record = record
        
        record.printRecord()
        record.verifyRecord()
        database.openConnection()
        database.saveRecord(record)
        database.closeConnection()
        record.updateAsSavedToDb()
        
        return record
    }
}

var record: Record = BasicRecord(savedToDb: false)
let database = SqlDb()

record = RecordBridge.saveRecord(recordToSave: record, database: database)
assert(record.savedToDb)

以上是关于swift Swift中桥接模式的示例的主要内容,如果未能解决你的问题,请参考以下文章

Java笔记-Java中桥接模式

java中桥接模式详解和使用方法

vmware中桥接模式,NAT模式,主机模式的区别

VMware中桥接模式,NAT,仅主机的区别

VMWare中桥接NATHost-only

iOS 图表工具charts之LineChartView