I. Overview
Concept
An operation that acts on individual objects in an object group. It allows you to define new actions that act on these objects without changing the objects themselves.
Introduced
Imagine a scenario in which a large number of references to various objects are placed in a collection, and when they are taken out they need to perform different actions depending on the specific type of these objects, we have the following scenario:
Public voidShow (Collection c) {Iterator it=C.iterator (); while(It.hasnext ()) {Object o=It.next (); if(OinstanceofInteger) { //an integer corresponding to the operation}Else if(OinstanceofString) { //Action for string}Else if(OinstanceofCollection) { //Collection The corresponding operation}Else { //omit a number of else if } } }
Without analyzing what's wrong with this code, we're introducing a solution: Visitor patterns-decoupling operations on data structures and structures
UML diagram
Java design Pattern (23)-the visitor pattern for behavioral patterns