LoginSignup
0
0

More than 3 years have passed since last update.

visitor pattern

Last updated at Posted at 2019-05-20

visitor pattern

オブジェクト構造上の要素で実行されるオペレーションを表現する。

結果

pros

オブジェクト構造に対して新しいオペレーションを追加しやすい
構造に対するオペレーションをビジターに閉じ込め、構造の要素のクラスを汚さない

cons

構造に新しい要素を加えることを難しくする。
構造の要素のクラスがビジターが働くのに十分なインターフェイスを後悔する必要がある。
これはカプセル化を緩くせざるをえないケースがある。

example

protocol EquipmentVisitorElementProtocol {
    func accept(visitor: EquipmentVisitorProtocol)
}

class Cable: EquipmentVisitorElementProtocol {
    func Accept(visitor: EquipmentVisitorElementProtocol) {
        visitor.visitCable(cable: self)
    }
}

class Part: EquipmentVisitorElementProtocol {
    func Accept(visitor: EquipmentVisitorElementProtocol) {
        visitor.visit(part: self)
    }
}

protocol EquipmentVisitorProtocol {
    func visitCable(cable: Cable)
    func visitPart(part: Part)
}

class PriceEquipmentVisitor: EquipmentVisitorProtocol {
    private var price: Int

    func visitCable(cable: Cable) {
        self.totalPrice += cable.price
    }

    func visitPart(part: Part) {
        self.totalPrice += part.specialPrice
    }
}

ex

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0