The Visitor

Intent: Set up a structure that allows the addition of operations across a variety of classes without changing the classes.

Example: A system that allows for the drawing of primitive, vector-based graphical objects (shapes) might need to allow for various transformational operations to be performed on these shapes, where the nature of the operation would vary based on which shape it is applied to. To “expand” a rectangle, for instance, involves multiplying its corners by a given factor. To “expand” a circle means to increase its radius. To “rotate” a square involves sine and cosine (sin and cos) calculations (trigonometry). To “rotate” a circle probably does nothing.

The visitor would allow for these operations to be extensible; additional kinds of transformations could be added without having to change the design of the shape objects.

images

Figure 21: Visitor example diagram.

Qualities and Principles: The visitor enables open-closedness where the operations are concerned. Each visitor object is about one set of operations. The visited objects (shapes, in the example) are also strongly cohesive; they are only responsible for selecting the correct method to call on the visitor. Clients do not couple to specific visitors or specific visited objects. The accept(Visitor) method they call is established at the abstract level, and takes an abstraction as its only parameter. All visitors and visited objects are thus interchangeable.

Testing: Both the visitor and the visited objects can be tested by using a mock (see p. 38) of the opposite interface.

  • The test of a visitor would ensure that the operations performed are correct in each case.
  • The test of a visited object would ensure it calls the correct method on the visitor interface.

Questions and Concerns: This design allows for the addition of new visitors very cleanly. It does not allow for the easy addition of visited objects, however, as the visitor interface is dependent on the specific types that currently exist in the visited structure. Adding to that structure would require maintenance of all existing visitors. This is not a “failing of the pattern”; it is simply a reality. In the example, adding a new shape will require determining how to perform each existing transformation upon it.

For more information: https://tinyurl.com/y52orvko

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset