Vistor Mode: 访问者模式
访问者在获得权限的之后,可以访问被访者的各项内容,同时,不能影响到被访者的属性,这样才是一个文明的访问者。
Visitor mode can isolate the algorithm and the object which algorithm affect. (Depart the server and the visitor). It put the new behaviors into a Visitor
class, then pass the existed object’s reference to the visitor to do the behaviors. It just visit the data of the object, but not change the original data.
访问者模式可以隔离算法和被这个算法影响的对象(分离服务者和访问者)。它将新的行为放置在一个称为 “访问者” 的对象中,然后传递原有对象的引用来执行一些行为。它只是访问对象数据,而没有改变源数据。
protocol Visitor {
func visit(d: Dog)
func visit(c: Cat)
func visit(h: Horse)
}
protocol Element {
func accept(v: Visitor)
}
// Element A
class Dog: Element {
var name = "dog"
var age = 0
func accept(v: Visitor) {
v.visit(d: self)
}
}
// Element B
class Cat: Element {
var name = "cat"
var age = 1
func accept(v: Visitor) {
v.visit(c: self)
}
}
// Element C
class Horse: Element {
var name = "horse"
var age = 2
func accept(v: Visitor) {
v.visit(h: self)
}
}
// Visitor 1
class NameVisitor: Visitor {
func visit(d: Dog) {
print(d.name)
}
func visit(c: Cat) {
print(c.name)
}
func visit(h: Horse) {
print(h.name)
}
}
// Visitor 2
class AgeVisitor: Visitor {
func visit(d: Dog) {
print("Dog age: \(d.age)")
}
func visit(c: Cat) {
print("Cat age: \(c.age)")
}
func visit(h: Horse) {
print("Horse age: \(h.age)")
}
}
let dog = Dog()
let cat = Cat()
let horse = Horse()
let nameVisitor = NameVisitor()
let ageVisitor = AgeVisitor()
dog.accept(v: nameVisitor) // dog 接受了 nameVistor 的访问,dog 把自己引用暂时交给 nameVistor 使用。
cat.accept(v: nameVisitor)
horse.accept(v: nameVisitor)
dog.accept(v: ageVisitor)
cat.accept(v: ageVisitor)
horse.accept(v: ageVisitor)
以上代码中,元素有 dog、cat、horse,访问者有 nameVistor、ageVistor。访问者得到被访者的接受之后(被访者把自己的引用给予访问者),才有权访问。