基本概念
Visitor Pattern: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. →
(When should you consider implementing this patterns? If you need to change the logic of various operations.)
实现代码
元素
具体元素
访问者
具体访问者
测试类
Q & A
Are there any drawbacks associated with this pattern?
If you need to frequently add new concrete classes to an existing architecture, the visitor hierarchy becomes difficult to maintain.
(lose the power of encapsulation↓ )
Why are you saying that a visitor class can violate the encapsulation?
Because it tends to require detailed knowledge of the concrete elements it's working on, and then it can modify that information, while encapsulation is the object-oriented principle of hiding the internal behavior of an object by only exposing a limited interface.
Why does this pattern compromise the encapsulation
Because it relies on an external object to operate on the internal state or data of a class.