设计模式之 Vistor 访问者模式:Swift 实现

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。访问者得到被访者的接受之后(被访者把自己的引用给予访问者),才有权访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值