中介者模式(Mediator Pattern):定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互.
中介者模式显示生活中场景比较多,买房和卖房者通过中介进行房屋交易,中介持有买卖双方的信息,但是买卖双方不知道对方信息, 网络斗地主平台根据输赢结果对参与斗地主的人员账户进行信息进行更新.以斗地主为例:
class Colleague {
var mediator:LeaderMediator?
var cashMoney:Float = 0
}
class ColleagueA:Colleague {
func winMoneyFromB(money:Float) {
self.mediator?.changeMoney(action: "ColleagueA", money: money)
}
}
class ColleagueB:Colleague {
func winMoneyFromA(money:Float) {
self.mediator?.changeMoney(action: "ColleagueB", money: money)
}
}
class Mediator {
var colleagueA:ColleagueA?
var colleagueB:ColleagueB?
convenience init(a:ColleagueA?,b:ColleagueB?) {
self.init()
colleagueA = a
colleagueB = b
}
func changeMoney(action:String,money:Float) {}
}
class LeaderMediator:Mediator {
override func changeMoney(action: String, money: Float) {
if action == "ColleagueA" {
self.colleagueA?.cashMoney += money
self.colleagueB?.cashMoney -= money
} else if action == "ColleagueB" {
self.colleagueA?.cashMoney -= money
self.colleagueB?.cashMoney += money
}
}
}
let colleagueA:ColleagueA = ColleagueA()
let colleagueB:ColleagueB = ColleagueB()
colleagueA.cashMoney = 100
colleagueB.cashMoney = 100
print("A当前现金:\(colleagueA.cashMoney)---B当前的现金:\(colleagueB.cashMoney)")
let mediator:LeaderMediator = LeaderMediator(a: colleagueA, b: colleagueB)
colleagueA.mediator = mediator
colleagueB.mediator = mediator
colleagueA.winMoneyFromB(money: 20)
print("A当前现金:\(colleagueA.cashMoney)---B当前的现金:\(colleagueB.cashMoney)")
colleagueB.winMoneyFromA(money: 50)
print("A当前现金:\(colleagueA.cashMoney)---B当前的现金:\(colleagueB.cashMoney)")
中介者模式的优点:
1.降低了系统对象之间的耦合性,使得对象易于独立的被复用.
2.提高系统的灵活性,使得系统易于扩展和维护.
中介者模式的缺点:
中介者模式的缺点是显而易见的,因为这个“中介“承担了较多的责任,所以一旦这个中介对象出现了问题,那么整个系统就会受到重大的影响.