本文大部分內(nèi)容翻譯至《Pro Design Pattern In Swift》By Adam Freeman太援,一些地方做了些許修改贪惹,并將代碼升級(jí)到了Swift2.0,翻譯不當(dāng)之處望多包涵债朵。
橋接模式(The Bridge Pattern)
橋接模式把事物對(duì)象和其具體行為啦桌、具體特征分離開來褪迟,使它們可以各自獨(dú)立的變化美浦。事物對(duì)象僅是一個(gè)抽象的概念。如“圓形”戚哎、“三角形”歸于抽象的“形狀”之下裸诽,而“畫圓”、“畫三角”歸于實(shí)現(xiàn)行為的“畫圖”類之下型凳,然后由“形狀”調(diào)用“畫圖”丈冬。
示例工程
OS X Command Line Tool工程:
Comms.swift
protocol ClearMessageChannel {
func send(message:String)
}
protocol SecureMessageChannel {
func sendEncryptedMessage(encryptedText:String)
}
class Communicator {
private let clearChannel:ClearMessageChannel
private let secureChannel:SecureMessageChannel
init (clearChannel:ClearMessageChannel, secureChannel:SecureMessageChannel) {
self.clearChannel = clearChannel
self.secureChannel = secureChannel
}
func sendCleartextMessage(message:String) {
self.clearChannel.send(message);
}
func sendSecureMessage(message:String) {
self.secureChannel.sendEncryptedMessage(message)
}
}
Communicator提供了允許傳送標(biāo)準(zhǔn)信息和安全信息的方法。操作這些信息的機(jī)制是 ClearMessageChannel協(xié)議和SecureMessageChannel 協(xié)議甘畅。
這里我們將創(chuàng)建兩種不同的網(wǎng)絡(luò)機(jī)制來傳輸信息:有線傳輸和無線傳輸埂蕊。
Channels.swift
class Landline : ClearMessageChannel {
func send(message: String) {
print("Landline: \(message)")
}
}
class SecureLandLine : SecureMessageChannel {
func sendEncryptedMessage(message: String) {
print("Secure Landline: \(message)")
}
}
class Wireless : ClearMessageChannel {
func send(message: String) {
print("Wireless: \(message)")
}
}
class SecureWireless : SecureMessageChannel {
func sendEncryptedMessage(message: String) {
print("Secure Wireless: \(message)")
}
}
然后我們看main.swift:
main.swift
var clearChannel = Landline()
var secureChannel = SecureLandLine()
var comms = Communicator(clearChannel: clearChannel, secureChannel: secureChannel)
comms.sendCleartextMessage("Hello!")
comms.sendSecureMessage("This is a secret")
運(yùn)行程序:
Landline: Hello!
Secure Landline: This is a secret
理解橋接模式解決的問題
從上圖可以看出,問題在于每一次我們?cè)黾右粋€(gè)新的機(jī)能或者一個(gè)新的平臺(tái)疏唾,都會(huì)導(dǎo)致實(shí)現(xiàn)類的數(shù)量急劇的增加粒梦。比如我們?cè)僭黾右粋€(gè)Chanel,那么實(shí)現(xiàn)類將會(huì)增加到6個(gè)荸实。這就是所謂的類爆炸式層級(jí)問題。
理解橋接模式
橋接模式從實(shí)現(xiàn)中分離出一個(gè)抽象缴淋,這樣他們都能各自獨(dú)立的變化准给。
Tip:分離共通和特定功能是最有效的辦法。
在示例中重抖,特定功能是每一個(gè)平臺(tái)使用一個(gè)特殊的網(wǎng)絡(luò)來傳輸信息露氮,共通功能是傳輸信息的準(zhǔn)備。第一步是定義每一個(gè)協(xié)議---信息和傳輸钟沛。然后是創(chuàng)建實(shí)現(xiàn)類畔规。
實(shí)現(xiàn)橋接模式
處理信息
首先我們處理共通功能--信息。
Messages.swift
import Foundation
protocol Message {
init (message:String)
func prepareMessage()
var contentToSend:String { get }
}
class ClearMessage : Message {
private var message:String
required init(message:String) {
self.message = message
}
func prepareMessage() {
// no action required
}
var contentToSend:String {
return message
}
}
class EncryptedMessage : Message {
private var clearText:String
private var cipherText:String?
required init(message:String) {
self.clearText = message
}
func prepareMessage() {
cipherText = String(clearText.characters.reverse())
}
var contentToSend:String {
return cipherText!
}
}
處理傳輸
Channels.swift
protocol Channel {
func sendMessage(msg:Message)
}
class LandlineChannel : Channel {
func sendMessage(msg: Message) {
print("Landline: \(msg.contentToSend)")
}
}
class WirelessChannel : Channel {
func sendMessage(msg: Message) {
print("Wireless: \(msg.contentToSend)")
}
}
創(chuàng)建橋
最后恨统,我們需要?jiǎng)?chuàng)建一個(gè)類來將Communicator類和Message協(xié)議叁扫,Channel協(xié)議連接起來三妈。
Bridge.swift
class CommunicatorBridge : ClearMessageChannel, SecureMessageChannel {
private var channel:Channel
init(channel:Channel) {
self.channel = channel
}
func send(message: String) {
let msg = ClearMessage(message: message);
sendMessage(msg)
}
func sendEncryptedMessage(encryptedText: String) {
let msg = EncryptedMessage(message: encryptedText)
sendMessage(msg)
}
private func sendMessage(msg:Message) {
msg.prepareMessage()
channel.sendMessage(msg)
}
}
最后我們修改main.swift:
main.swift
var bridge = CommunicatorBridge(channel: LandlineChannel())
var comms = Communicator(clearChannel: bridge, secureChannel: bridge)
comms.sendCleartextMessage("Hello!")
comms.sendSecureMessage("This is a secret")
運(yùn)行程序:
Landline: Hello!
Landline: terces a si sihT
增加新的信息和傳輸
Comms.swift
protocol ClearMessageChannel {
func send(message:String)
}
protocol SecureMessageChannel {
func sendEncryptedMessage(encryptedText:String)
}
protocol PriorityMessageChannel {
func sendPriority(message:String)
}
class Communicator {
private let clearChannel:ClearMessageChannel
private let secureChannel:SecureMessageChannel
private let priorityChannel:PriorityMessageChannel
init (clearChannel:ClearMessageChannel, secureChannel:SecureMessageChannel, priorityChannel:PriorityMessageChannel) {
self.clearChannel = clearChannel
self.secureChannel = secureChannel
self.priorityChannel = priorityChannel
}
func sendCleartextMessage(message:String) {
self.clearChannel.send(message)
}
func sendSecureMessage(message:String) {
self.secureChannel.sendEncryptedMessage(message)
}
func sendPriorityMessage(message:String) {
self.priorityChannel.sendPriority(message)
}
}
如果不使用橋接模式,那么新增一個(gè)信息類型將要增加5個(gè)類莫绣。請(qǐng)看下圖:
而在橋接模式下畴蒲,添加相同的信息和傳輸只需要新增兩個(gè)類。
NewFeatures.swift
class SatelliteChannel : Channel {
func sendMessage(msg: Message) {
print("Satellite: \(msg.contentToSend)")
}
}
class PriorityMessage : ClearMessage {
override var contentToSend:String {
return "Important: \(super.contentToSend)"
}
}
接下來我們更新 Communicator 類:
Bridge.swift
class CommunicatorBridge : ClearMessageChannel, SecureMessageChannel,PriorityMessageChannel{
private var channel:Channel
init(channel:Channel) {
self.channel = channel
}
func send(message: String) {
let msg = ClearMessage(message: message);
sendMessage(msg)
}
func sendEncryptedMessage(encryptedText: String) {
let msg = EncryptedMessage(message: encryptedText)
sendMessage(msg)
}
func sendPriority(message: String) {
sendMessage(PriorityMessage(message: message))
}
private func sendMessage(msg:Message) {
msg.prepareMessage()
channel.sendMessage(msg)
}
}
最后main.swift:
main.swift
var bridge = CommunicatorBridge(channel: SatelliteChannel())
var comms = Communicator(clearChannel: bridge,secureChannel: bridge,
priorityChannel: bridge)
comms.sendCleartextMessage("Hello!")
comms.sendSecureMessage("This is a secret")
comms.sendPriorityMessage("This is important")
運(yùn)行程序:
Satellite: Hello!
Satellite: terces a si sihT
Satellite: Important: This is important
橋接模式的變形
最簡單的變形就是和工廠模式結(jié)合对室,這樣特定部分的選擇就會(huì)被隱藏起來模燥。
Channels.swift
class Channel {
enum Channels {
case Landline
case Wireless
case Satellite
}
class func getChannel(channelType:Channels) -> Channel {
switch channelType {
case .Landline:
return LandlineChannel()
case .Wireless:
return WirelessChannel()
case .Satellite:
return SatelliteChannel()
}
}
func sendMessage(msg:Message) {
fatalError("Not implemented")
}
}
class LandlineChannel : Channel {
override func sendMessage(msg: Message) {
print("Landline: \(msg.contentToSend)")
}
}
class WirelessChannel : Channel {
override func sendMessage(msg: Message) {
print("Wireless: \(msg.contentToSend)")
}
}
然后是NewFeatures.swift
class SatelliteChannel : Channel {
override func sendMessage(msg: Message) {
print("Satellite: \(msg.contentToSend)")
}
}
class PriorityMessage : ClearMessage {
override var contentToSend:String {
return "Important: \(super.contentToSend)"
}
}
修改Bridge.swift中的初始化方法:
Bridge.swift
...
init(channel:Channel.Channels) {
self.channel = Channel.getChannel(channel)
}
...
最后更新main.swift:
var bridge = CommunicatorBridge(channel:Channel.Channels.Satellite)
var comms = Communicator(clearChannel: bridge,secureChannel: bridge,
priorityChannel: bridge)
comms.sendCleartextMessage("Hello!")
comms.sendSecureMessage("This is a secret")
comms.sendPriorityMessage("This is important")
運(yùn)行程序,得到結(jié)果和上面的一樣:
Satellite: Hello!
Satellite: terces a si sihT
Satellite: Important: This is important