Swift World:设计模式-代理

今天,我们将讨论代理模式。 在这种模式下,代理是一个对象,可以帮助我们访问另一个对象。 它只是将实际工作委托给该对象或更改其行为。 下图描述了角色及其关系。

从代理模式开始— Wikipedia

代理模式在Cocoa中广泛使用,它甚至具有特定的NSProxy类。 另一个示例是UIApperance协议和其他相关类型。

我们将继续使用我们的汽车系统。

protocol Car { 
func drive ()
}
 class Sedan : Car { 
func drive () {
print ("drive a sedan")
}
}

自动驾驶汽车现在是热门话题。 因此,让我们构建自己的。 实际上,它不是从头开始构建的,而是通过自动驾驶系统增强了我们当前的汽车。 因此,它具有内部汽车实例,并将驾驶委托给汽车。 但是作为自动驾驶汽车,它会自动控制汽车。 委托和变更是代理在此模式下的工作。

 class AutonomousCar : Car { 
var car: Car
 init (car: Car ) { 
self. car = car
}
 func drive () { 
car .drive ()
print ("by self-driving system")
}
}

让我们看看如何驱动它。

 //usage 
let sedan = Sedan ()
let autonomousCar = AutonomousCar (car: sedan)
autonomousCar .drive ()