ahcode0919
8/21/2016 - 9:04 PM

Example of the bridge pattern in Swift

Example of the bridge pattern in 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)