Visitor-Visitor Mode
Purpose
Without changing the classes in a hierarchy, define new operations that act on each element of the class.
CaseThere are different device Equipment, such as Chassis and FloppyDisk. Some people want to know its performance, but some want to know its price, and some may want to know other information, such as manufacturer and manufacturing materials. However, when an Equipment class is defined and a subclass is defined, you need to change all classes to add new operations. In this case, you can consider using the Visitor mode. In the Visitor mode, you only need to provide an accept (Visitor *) method in Equiment, and pass the information to the visitor object through the Visitor method of the Visitor class:
Equipment provides an accept operation so that it can work with a visitor:
class Equipment
{
public:
virtual void accept(Visitor* v) = 0;
};
Perform the accept operation in the subclass:
class FloppyDisk : public Equipment
{
public:
virtual void accept(Visitor* v);
};
void FlopyyDisk::accept(Visitor* v)
{
v->visit(this);
}
For example, if Chassis has sub-devices, you need to independently call the accept operation on each sub-device:
class Chassis : public Equipment
{
public:
virtual void accept(Visitor* v);
private:
std::vector m_parts;
};
void Chassis::accept(Visitor* v)
{
for(int i = 0; i < m_parts.size(); ++i)
m_parts[i]->accept(v);
v->visit(this);
}
Visitor provides methods to access the Equipment object:
class Visitor
{
public:
virtual void visit(FloppyDisk* floppyDisk) = 0;
virtual void visit(Chassis* chassis) = 0;
};
Subclass mainly redefines two methods to get the desired results.
ApplicabilityAn object structure contains many class objects which have different interfaces and want to perform operations on these objects dependent on their specific classes. You need to perform many different and unrelated operations on the objects in an object structure, and want to avoid these operations from polluting the class of the objects. Classes that define the object structure are rarely changed, but new operations are often needed in this structure.