情景
- 每個人需要找房子
- 用戶直接找房不方便
- 于是呢撰糠,用戶和房產中介有一個協(xié)議
- 中介負責找房子,找到符合用戶滿意的房子中介就可以直接拿中介費
具體實現(xiàn)
// 代理協(xié)議
protocol HelpDelegate{
func SomeHelp(other:Any)
}
//支付協(xié)議
@objc protocol Paydelegate{
@objc optional func paymoney(money: Int,agent:Any) //可選類型
}
Person
class Person : Paydelegate{
var name:String = ""
var delegate:HelpDelegate?
private var acount = 10000
private var wantedprice = (0,0)
init(_ name:String,wantedprice:(Int,Int)) {
self.name = name
self.wantedprice = wantedprice
}
func findhouse() {
if (self.delegate != nil) {
self.delegate?.SomeHelp(other: self)
}
}
func paymoney(money: Int,agent:Any) {
acount -= money
print("\(self.name) 你支付了"+"\(money),賬戶余額"+"\(self.acount)"+"-------\(agent)")
}}
中介
class FcAgent:HelpDelegate {
var custom:[Person] = [Person]()
var delegate:Paydelegate?
func SomeHelp( other: Any) {
let per = other as! Person
print("\(self.name):尊敬的\(per.name), 我們給你找到房子啦水慨,地址在成都市高新區(qū),xxx小區(qū),水月洞天唉侄,請及時入住 ,月租450")
//得到房子租金
let price = 450
custom += [per]//添加到已完成找房數(shù)組
if (per.wantedprice.0 < price ) && (per.wantedprice.1 > price) {
//可以通知用戶交租金了
if self.delegate != nil {
self.delegate?.paymoney!(money: price,agent:self)
}
}
else{
}
}
var name:String = ""
init(_ name:String) {
self.name = name
}
}
//調用
let person = Person("張永昊",wantedprice: (300,500))
let agent = FcAgent("房產中介")
person.delegate = agent
agent.delegate = person
person.findhouse()
效果
房產中介:尊敬的張永昊, 我們給你找到房子啦野建,地址在成都市高新區(qū)属划,xxx小區(qū),水月洞天候生,請及時入住
張永昊 你支付了450同眯,賬戶余額9550-------FcAgent
好處
降低對象之間的耦合度
對象之間不需要直接關心具體的操作
與通知的區(qū)別
通知的方式可以多對多
代理方式一般用于一對多
能使用代理方式完成的也能使用通知的方式完成