Visitor pattern explained in the simplest snippets


First of all, what problem does this pattern solves?
See below:

class Person
{
public:
 void GetHomeWorkChecked();
};
void Test()
{
 Person *pPerson = new Person();
 pPerson->GetHomeWorkChecked();
}

Now we want add another operation, which is to get paycheck.
We could do this:

class Person
{
public:
 void GetHomeWorkChecked();
 void GetPaycheckIssued();
};

But what if we want no change in the Person class?
That’s when Visitor pattern comes into play:

class Person;
class Visitor
{
public:
 virtual void Visit(Person *pPerson) = 0;
};
class TeacherVisitor: public Visitor
{
public:
 void Visit(Person *pPerson)
 { printf("checking homework\n");  }
};
class BossVisitor: public Visitor
{
public:
 void Visit(Person *pPerson)
 { printf("issuing playchecked\n");  }
};
class Person
{
public:
 void accept(Visitor *pVisitor)
 { pVisitor->Visit(this); }
};
void Test()
{
 Person *pPerson = new Person();
 Visitor *pTeacher = new TeacherVisitor();
 Visitor *pBoss = new BossVisitor();
 pPerson->accept(pTeacher);//to get homework checked.
 pPerson->accept(pBoss);//to get paycheck issued.
}

You’ll see most explanations (either in the books or on the internet) is more complicated than mine. That’s because they made subclasses for Person. However, making subclasses is not the key of visitor pattern. They did that only because they want the visitor treats different kind of Persons differently.

Advertisements
Comments are closed.
%d bloggers like this: