Created
January 1, 2018 19:47
-
-
Save FONQRI/ffe624f4315420a02948e50212fffb17 to your computer and use it in GitHub Desktop.
visitor Design Pattern in c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <list> | |
#include <memory> | |
using namespace std; | |
// Forwards | |
class VisitorIntf; | |
// Abstract interface for Element objects | |
class ElementIntf { | |
public: | |
virtual ~ElementIntf(); | |
virtual string name() = 0; | |
virtual void accept(shared_ptr<VisitorIntf> object) = 0; | |
}; | |
ElementIntf::~ElementIntf() {} | |
// Abstract interface for Visitor objects | |
class VisitorIntf { | |
public: | |
virtual ~VisitorIntf(); | |
virtual void visit(ElementIntf *object) = 0; | |
}; | |
VisitorIntf::~VisitorIntf() {} | |
// Concrete element object | |
class ConcreteElement1 : public ElementIntf { | |
public: | |
string name(); | |
void accept(shared_ptr<VisitorIntf> object); | |
}; | |
string ConcreteElement1::name() { return "ConcreteElement1"; } | |
void ConcreteElement1::accept(shared_ptr<VisitorIntf> object) | |
{ | |
object->visit(this); | |
} | |
// Concrete element object | |
class ConcreteElement2 : public ElementIntf { | |
public: | |
string name(); | |
void accept(shared_ptr<VisitorIntf> object); | |
}; | |
string ConcreteElement2::name() { return "ConcreteElement2"; } | |
void ConcreteElement2::accept(shared_ptr<VisitorIntf> object) | |
{ | |
object->visit(this); | |
} | |
// Visitor logic 1 | |
class ConcreteVisitor1 : public VisitorIntf { | |
public: | |
void visit(ElementIntf *object); | |
}; | |
void ConcreteVisitor1::visit(ElementIntf *object) | |
{ | |
cout << "Visited " << object->name() << " using ConcreteVisitor1." << endl; | |
} | |
// Visitor logic 2 | |
class ConcreteVisitor2 : public VisitorIntf { | |
public: | |
void visit(ElementIntf *object); | |
}; | |
void ConcreteVisitor2::visit(ElementIntf *object) | |
{ | |
cout << "Visited " << object->name() << " using ConcreteVisitor2." << endl; | |
} | |
// Test main program | |
int main() | |
{ | |
list<shared_ptr<ElementIntf>> elementList1; | |
elementList1.push_back(make_shared<ConcreteElement1>()); | |
elementList1.push_back(make_shared<ConcreteElement2>()); | |
shared_ptr<VisitorIntf> visitor1 = make_shared<ConcreteVisitor1>(); | |
for (auto element : elementList1) { | |
element->accept(visitor1); | |
} | |
list<shared_ptr<ElementIntf>> elementList2; | |
elementList2.push_back(make_shared<ConcreteElement1>()); | |
elementList2.push_back(make_shared<ConcreteElement2>()); | |
shared_ptr<VisitorIntf> visitor2 = make_shared<ConcreteVisitor2>(); | |
for (auto element : elementList2) { | |
element->accept(visitor2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment