Skip to content

Instantly share code, notes, and snippets.

@ahcode0919
Last active August 19, 2020 20:42
Show Gist options
  • Save ahcode0919/cb98b2287733ac354d47e5415e182785 to your computer and use it in GitHub Desktop.
Save ahcode0919/cb98b2287733ac354d47e5415e182785 to your computer and use it in GitHub Desktop.
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 vary 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment