Visitor Mode
GOOD: Suitable for systems with stable data structures. It separates the data structure from the operations acting on the data structure so that the operation set
Advantage: it is easy to add a new operation, because adding a new operation is equivalent to adding a visitor. The visitor mode aggregates the related behavior into a visitor object.
[Html]
# Include <iostream>
# Include <string>
# Include <vector>
Using namespace std;
Class Man;
Class Woman;
// Action
Class Action
{
Public:
Virtual void GetManConclusion (Man * concreteElementA) = 0;
Virtual void GetWomanConclusion (Woman * concreteElementB) = 0;
};
// Succeeded
Class Success: public Action
{
Public:
Virtual void GetManConclusion (Man * concreteElementA)
{
Cout <"when a man succeeds, there is a great woman behind it" <endl;
}
Virtual void GetWomanConclusion (Woman * concreteElementB)
{
Cout <"when a woman succeeds, there is a useless man behind it" <endl;
}
};
// Failed
Class Failure: public Action
{
Public:
Virtual void GetManConclusion (Man * concreteElementA)
{
Cout <"when a man fails, there is a great woman behind it" <endl;
}
Virtual void GetWomanConclusion (Woman * concreteElementB)
{
Cout <"when a woman fails, there is a useless man behind it" <endl;
}
};
// Abstract human
Class Person
{
Public:
Virtual void Accept (Action * visitor) = 0;
};
// Man
Class Man: public Person
{
Public:
Virtual void Accept (Action * visitor)
{
Visitor-> GetManConclusion (this );
}
};
// Woman
Class Woman: public Person
{
Public:
Virtual void Accept (Action * visitor)
{
Visitor-> GetWomanConclusion (this );
}
};
// Object structure class
Class ObjectStructure
{
Private:
Vector <Person *> m_personList;
Public:
Void Add (Person * p)
{
M_personList.push_back (p );
}
Void Display (Action *)
{
Vector <Person *>: iterator p = m_personList.begin ();
While (p! = M_personList.end ())
{
(* P)-> Accept ();
P ++;
}
}
};
// Client
Int main ()
{
ObjectStructure * OS = new ObjectStructure ();
OS-> Add (new Man ());
OS-> Add (new Woman ());
Success * success = new Success ();
OS-> Display (success );
Failure * fl = new Failure ();
OS-> Display (fl );
Return 0;
}