根据设计模式的创始人的说法,在大多数情况下,您不需要访问者模式,但当您需要访问者模式时,您确实需要它。您可以看到,应用程序场景很少,但当您需要它时,它是必不可少的,因此本文开始学习最后一种设计模式-访问者模式。
[En]
In most cases you don't need the visitor pattern, but when you need the visitor pattern, you really need it, according to the founder of the design pattern. You can see that there are few application scenarios, but it is indispensable when you need it, so this article begins to learn about the last design pattern-the Visitor pattern.
一、概念理解
访问者模式概念:封装作用于对象结构中的元素的操作,允许您定义作用于这些元素的新操作,而无需更改它们的类。
[En]
Visitor pattern concept: encapsulates operations that act on elements in an object structure, allowing you to define new operations that act on those elements without changing their classes.
通俗的解释就是,系统中有一些固定结构的对象(元素),在其内部提供一个accept()方法用来接受访问者对象的访问,不同的访问者对同一元素的访问内容不同,所以使得相同的元素可以产生不同的元素结果。
比如在一个人事管理系统中,有多个工种的员工和多个老板,不同的老板对同一个员工的关注点是不同的,CTO可能关注的就是技术,CEO可能更注重绩效。
员工是一个稳定的元素,老板是可变的,对应的概念是:封装员工的一些操作,可以添加一个新的老板来访问同一个员工,而不需要更改Employee类。
[En]
The employee is a stable element, and the boss is changeable, and the corresponding concept is: encapsulating some operations of the employee, you can add a new boss to visit the same employee without changing the employee class.
访问者模式中有五个角色:抽象元素、具体元素、抽象访问者、具体访问者和结构元素。
[En]
There are five roles in the visitor pattern: abstract elements, concrete elements, abstract visitors, concrete visitors, and structural elements.
抽象元素:定义一个接受访问的方法accept,参数为访问者对象。
具体元素:提供接受访问者访问的具体实现调用访问者的访问visit,并定义额外的数据操作方法。
抽象访问者:这个角色主要是定义对具体元素的访问方法visit,理论上来说方法数等于元素(固定类型的对象,也就是被访问者)个数。