为其他对象(A)提供一种代理对象(B),并由改代理对象(B)控制对该对象(A)的访问
在代理模式中引入了一个新的代理对象,代理对象在客户端对象和目标对象之间起到中介的作用,它去掉客户不能看到的内容和服务或者增添客户需要的额外的新服务
代理模式类图
需求V1 :不想做饭,想用APP点个外卖
协议类
protocol DoSomethingDelegate {
func buySomething()
}
委托类
class Person {
weak var delegate : APP?
func buy() {
if self.delegate != nil && ((self.delegate?.buySomething) != nil) {
self.delegate?.buySomething()
}
}
}
代理类
class APP :DoSomethingDelegate{
func buySomething() {
print("外卖")
}
}
客户端调用
let per = Person.init()
let app = APP.init()
per.delegate = app
per.buy()
log:
//外卖