element.h
#ifndef ELEMENT_H
#define ELEMENT_H
#include "visitor.h"
class Element
{
public:
Element() {}
virtual void accept(Visitor *visitor) = 0;
};
class ConcreteElementA : public Element
{
public:
ConcreteElementA() {}
void accept(Visitor *visitor)
{
visitor->visitConcreteElementA(this);
}
};
class ConcreteElementB : public Element
{
public:
ConcreteElementB() {}
void accept(Visitor *visitor)
{
visitor->visitConcreteElementB(this);
}
};
#endif // ELEMENT_H
visitor.h
#ifndef VISITOR_H
#define VISITOR_H
#include <QtDebug>
#include "element.h"
class Element;
class ConcreteElementA;
class ConcreteElementB;
class Visitor
{
public:
Visitor() {}
virtual void visitConcreteElementA(ConcreteElementA *concreteElementA){}
virtual void visitConcreteElementB(ConcreteElementB *concreteElementB){}
};
class ConcreteVisitor1 : public Visitor
{
public:
ConcreteVisitor1() {}
void visitConcreteElementA(ConcreteElementA *concreteElementA)
{
qDebug() << "ConcreteVisitor1 visitConcreteElementA";
}
void visitConcreteElementB(ConcreteElementA *concreteElementB)
{
qDebug() << "ConcreteVisitor1 visitConcreteElementB";
}
};
class ConcreteVisitor2 : public Visitor
{
public:
ConcreteVisitor2() {}
void visitConcreteElementA(ConcreteElementA *concreteElementA)
{
qDebug() << "ConcreteVisitor2 visitConcreteElementB";
}
void visitConcreteElementB(ConcreteElementA *concreteElementB)
{
qDebug() << "ConcreteVisitor2 visitConcreteElementB";
}
};
#endif // VISITOR_H
objectStructure.h
#ifndef OBJECTSTRUCTURE_H
#define OBJECTSTRUCTURE_H
#include <QList>
#include "element.h"
#include "visitor.h"
class ObjectStructure
{
public:
ObjectStructure() {}
void attach(Element *element)
{
m_elements.append(element);
}
void detach(Element *element)
{
for(int i = m_elements.count(); i > 0; i++)
{
if(m_elements.at(i-1) == element)
{
m_elements.removeAt(i-1);
}
}
}
void accept(Visitor *visitor)
{
foreach (Element *e, m_elements) {
e->accept(visitor);
}
}
private:
QList<Element*> m_elements;
};
#endif // OBJECTSTRUCTURE_H
main.cpp
#include <QApplication>
#include "objectStructure.h"
#include "element.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ObjectStructure *o = new ObjectStructure();
ConcreteElementA *aa = new ConcreteElementA();
ConcreteElementB *bb = new ConcreteElementB();
o->attach(aa);
o->attach(bb);
ConcreteVisitor1 *v1 = new ConcreteVisitor1();
ConcreteVisitor2 *v2 = new ConcreteVisitor2();
o->accept(v1);
o->accept(v2);
return a.exec();
}
UML
来源:https://blog.csdn.net/sinat_33859977/article/details/99308990