Skip to main content

Visitor Pattern

It is often require to separate an algorithms from the data it operates on.
For example say that we have some inter process communication messages that needs to be sent out from a TCP channel.
The message is the parent class and different messages are derived from this class.
The sub-message class object that has some member variables that are used to pack the real messages to be sent out.
The straightforward way of doing this is to have a virtual function pack() defined in the message class itself and implement it in every sub-message class and call it whenever we need the message to be generated.
However this is not that efficient because if we need to change the structure or the format of the messages that we need to send out, the pack () of the that specific class should be modified.
If all messages require a addition of a different field all messages have to be changed.

Not if you have introduced the visitor pattern. Compare the visitor pattern with the standard approach. First off the bad example followed by the same thing done using the visitor pattern.

#include <iostream>
#include <string>
#include <list>
using namespace std;
class Employee {
public:
virtual string reportQtdHoursAndPay() = 0;
};
class HourlyEmployee : public Employee {
public:
virtual string reportQtdHoursAndPay() {
//generate the line for this hourly employee
string report = "Generated report line for Hourly Employee";
return report;
}
};
class SalariedEmployee : public Employee {
public:
virtual string reportQtdHoursAndPay() {
string report = "Generated report line for Salaried Employee";
return report;
} // do nothing
};
int main()
{
std::list<Employee*> lst_Employees;
HourlyEmployee he1,he2;
SalariedEmployee se1,se2;
lst_Employees.push_back(&he1);
lst_Employees.push_back(&he2);
lst_Employees.push_back(&se1);
lst_Employees.push_back(&se2);
for (std::list<Employee*>::iterator it=lst_Employees.begin(); it != lst_Employees.end(); ++it)
std::cout << (*it)->reportQtdHoursAndPay() << std::endl;
return 0;
}
// Example program
#include <iostream>
#include <string>
#include <list>
using namespace std;
class HourlyEmployee;
class SalariedEmployee;
class EmployeeVisitor { // holds the algorithm
public:
virtual void visit(HourlyEmployee* he) = 0;
virtual void visit(SalariedEmployee* se) = 0;
};
class Employee {
public:
virtual void accept(EmployeeVisitor* p) = 0;
};
class HourlyEmployee : public Employee {
public:
virtual void accept(EmployeeVisitor* p) {
//generate the line for this hourly employee
//string report = "Generated report line for Hourly Employee";
//return report;
p->visit(this);
}
};
class SalariedEmployee : public Employee {
public:
virtual void accept(EmployeeVisitor* p) {
//string report = "Generated report line for Salaried Employee";
//return report;
p->visit(this);
} // do nothing
};
class QtdHoursAndPayReport : public EmployeeVisitor {
public:
void visit(HourlyEmployee* he) {
// generate the line of the report.
cout << "Generated report line for Hourly Employee" << endl;
}
void visit(SalariedEmployee* se) {
cout << "Generated report line for Salaried Employee" << endl;
}
};
int main()
{
std::list<Employee*> lst_Employees;
HourlyEmployee he1,he2;
SalariedEmployee se1,se2;
lst_Employees.push_back(&he1);
lst_Employees.push_back(&he2);
lst_Employees.push_back(&se1);
lst_Employees.push_back(&se2);
QtdHoursAndPayReport* v = new QtdHoursAndPayReport();
for (std::list<Employee*>::iterator it=lst_Employees.begin(); it != lst_Employees.end(); ++it)
(*it)->accept(v);
return 0;
}
view raw visitor.cpp hosted with ❤ by GitHub

Comments

Popular posts from this blog

Detaching a process from terminal - exec(), system(), setsid() and nohup

Linux processes are created by fork() and exec(). The very first process of POSIX systems is init and subsequent processes are derived from the init as parent. These subsequent processes are child processes. During forking the parent process copies itself - with all I/O, address space, stack, everything. The only thing that is different is the process ID. The parent and child will have 2 different process IDs. The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows: execl("/bin/sh", "sh", "-c", command, (char *) 0); system() returns after the command has been completed. system() executes a command specified in command by calling /bin/sh -c command , and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.  system() calls are often made within programs to execut...

C++ Callbacks using function pointers vs boost bind +boost function

In C, the most common uses of callbacks are as parameters to library functions like qsort , and as callbacks for Windows functions, etc. For example you might have a library that provides some sorting functions but you want to allow the library user to provide his own sorting function. Since the arguments and the return values do not change depending on the sorting algorithm, this can be facilitated in a convenient manner using function callbacks. Callbacks are also used as event listeners. onMouseClick(), onTerminalInput(), onData(), onConnectionStatus(), onRead() are probably some examples you've already seen in different libraries. The libraries have these callback functions and the users of the library are supposed to implement them. The library has a function pointer to these functions and calls them on their event loop which will invoke the code of the inherited classes of the library user. The implementation of function pointers is simple: they are just "code p...

sprintf, snprintf, strcpy, strncpy and sizeof operator

"C library functions such as strcpy (), strcat (), sprintf () and vsprintf () operate on null terminated strings and perform no bounds checking." "snprintf is safer than sprintf" What do these statements really mean? int sprintf ( char * str , const char * format , ... )  int snprintf ( char * s, size_t n, const char * format, ... );  char * strcpy ( char * destination, const char * source ); char * strncpy ( char * destination, const char * source, size_t num );   The usage is something like; char* msg1 = new char[10]; strcpy(msg1, "test"); // 1 char buffer[128]; sprintf(buffer, "%s", msg); //2 strcpy : Copies bytes until it finds a 0-byte in the source code. The string literal "test" has 4 characters and a terminating null character at end, therefore needs 5 characters at least on msg1.  Is this dangerous? Yes, because if the source message is not null terminated it will read until a null character ...