Skip to main content

Posts

Showing posts from May, 2015

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.