中介者设计模式的目的是实现多个对象之间的解耦合,把原来对象之间复杂的耦合关系全部迁移到中介者身上,对象之间不直接进行交流,他们通过中介来转达消息。
举一个非常容易理解的场景,现在有很多房屋中介机构,提供租房的业务,房屋业主跟中介对接,中介跟租客对接,房屋业主不跟租客直接对接。
1.定义一个抽象的经纪人类,数组customers存放所有用户,包含添加用户,删除用户,通知用户的方法
open class Broker {
public var customers: [Customer] = []
public func addCutsomer(_ customer: Customer) {
customers.append(customer)
}
public func removeCustomer(_ customer: Customer) {
guard let index = customers.firstIndex(where: {
$0 === customer
}) else {
return
}
customers.remove(at: index)
}
public func notifyCustomer(by customer: Customer, closure: (Customer) -> Void) {
customers.forEach {
guard $0 !== customer else { return }
closure($0)
}
}
}
2.定义一个具体的房屋经济人类,遵守BrokerProtocol协议,执行添加用户,发送消息的方法
public protocol BrokerProtocol: class {
func addCustomer(_ customer: Customer)
func sendMessage(_ message: String, by customer: Customer)
}
public class RealEatateBroker: Broker {
}
extension RealEatateBroker: BrokerProtocol {
public func addCustomer(_ customer: Customer) {
self.addCutsomer(customer)
}
public func sendMessage(_ message: String, by customer: Customer) {
notifyCustomer(by: customer) {
$0.customer(customer, didSendMesaage: message)
}
}
}
3.定义一个用户类,遵守CustomProtocol协议,弱引用一个遵守BrokerProtocol协议的属性broker。
用户发送消息会告诉broker,broker再将消息转发给其他用户,其他用户收到消息,会调用CustomProtocol协议中的方法。
public protocol CustomerProtocol: class {
func customer(_ customer: CustomerProtocol, didSendMesaage message: String)
}
public class Customer {
public let name: String
public weak var broker: BrokerProtocol?
public init(name: String, broker: BrokerProtocol) {
self.name = name
self.broker = broker
broker.addCustomer(self)
}
public func sendMessage(_ message: String) {
print("\(name) sent: \(message)")
broker?.sendMessage(message, by: self)
}
}
extension Customer: CustomerProtocol {
public func customer(_ customer: CustomerProtocol, didSendMesaage message: String) {
print("\(name) received: \(message)")
}
}
4.运行测试代码,用户Jack发送一条消息,Tom和Steven会接收到这条消息。从此实现用户之间的交互。
let broker = RealEatateBroker()
let jack = Customer(name: "Jack", broker: broker)
let tom = Customer(name: "Tom", broker: broker)
let steven = Customer(name: "Steven", broker: broker)
jack.sendMessage("What kind of discount do we get?")
5.输出结果
Jack sent: What kind of discount do we get?
Tom received: What kind of discount do we get?
Steven received: What kind of discount do we get?
Custom通过CustomProtocol协议与Broker交互,接收消息的人并不会知道消息是谁发送的,从而实现对象之间的解耦合。
如果已经熟悉了观察者模式,再去学习中介者模式,就会发现二者是非常相似的。
中介者模式强调的是,将对象与对象之间的强耦合关系,全部转移到中介者身上,从网状结构转换成星形结构,对象和对象之间的交互也是双向的。
A,B,C如果都添加到了中介者的集合之后,如果A发动了状态的变化,B和C都会接收到消息,并作出反馈,A接收到反馈之后,可能会有一些操作,关注的重点是A B C 之间的交互,三者之间是平级的关系。
观察者模式强调的是发布-订阅,B和C决定观察A某个属性的变化,B和C等A的属性变化发布之后,执行自己的操作,A是完全不需要知道的,并且也不需要对B和C的反馈做出反应。A的等级是要高于B和C的。
网友评论