Thursday, 18 June 2015

Visitor Design Pattern

Visitor Design Pattern in Cpp with examples:

This pattern is a type of multiple dispatching.

It is possible to add the new polymorphic methods to that hierarchy, which means that normally you would have to add something to the base class interface.

The visitor pattern allows you to extend the interface of the primary type by creating a
Separate class hierarchy of type visitor to virtualize the operations performed upon the
Primary type.

The objects of the primary type simply “accept” the visitor, then call the visitor’s dynamically-bound member function.

The below is the example for visitor design pattern.


#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

#include <cstdlib>

#include <ctime>

using namespace std;
class Child1;

class Child2;

class Child3;

class TesClass {

public:

virtual void Verify (Child1* pcClas) = 0;

virtual void Verify (Child2* pcClas) = 0;

virtual void Verify (Child3* pcClas) = 0;

virtual ~TesClass () {}

};

class SuperMost

{

public:

virtual void MyBaseFun (TesClass&) = 0;

virtual ~SuperMost () {}

};

class Child3 : public SuperMost {

public:

virtual void MyBaseFun (TesClass& ocObj) {

ocObj.Verify (this);

}

};

class Child1 : public SuperMost {

public:

virtual void MyBaseFun(TesClass& ocObj) {

ocObj.Verify(this);

}

};

class Child2 : public SuperMost {

public:

virtual void MyBaseFun(TesClass& ocObj) {

ocObj.Verify(this);

}

};

class StringVal : public TesClass

{

string MySTr;

public:

operator const string& ()

 { return MySTr; }

virtual void Verify(Child3*)

{

MySTr = "Child3";

}

virtual void Verify (Child1*)

{

MySTr = "Child1";

}

virtual void Verify (Child2*)

{

MySTr = "Child2";

}

};

class TestClass2 : public TesClass

{

public:

virtual void Verify (Child1*)

{

cout << "TestClass2 and Child1\n";

}

virtual void Verify (Child2*)

{

cout << "TestClass2 and Child2\n";

}

virtual void Verify (Child3*)

{

cout << "TestClass2 and Child3\n";

}

};

struct stGeneral

{

stGeneral ()

  { srand (time(0)); }

SuperMost* operator()()

{

switch (rand () % 3)

{

default:

case 0: return new Child1;

case 1: return new Child2;

case 2: return new Child3;

}

}

};

int _tmain (int argc, _TCHAR* argv[])

{
 vector<SuperMost*> ocObj (10);

generate(ocObj.begin (), ocObj.end (), stGeneral());

vector<SuperMost*>::iterator it;

StringVal sval;

for(it = ocObj.begin (); it != ocObj.end(); it++) {

 (*it)->MyBaseFun(sval);

  cout << string(sval) << endl;

}

TestClass2 TestClass2;

for(it = ocObj.begin(); it != ocObj.end(); it++)

  (*it)->MyBaseFun(TestClass2);

  getchar ();

 return 0;

}



No comments: