#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Element;
class Visitor
{
public:
virtual void visitElementOne(Element* pobjElement) = 0;
virtual void visitElementTwo(Element* pobjElement) = 0;
};
class Element
{
public:
Element(const string& strName) : m_strName(strName) {}
virtual void accept(Visitor* pobjVisitor) = 0;
void setName(const string& strName) { m_strName = strName; }
const string& getName() { return m_strName; }
protected:
string m_strName = "";
};
class VisitorOne : public Visitor
{
public:
virtual void visitElementOne(Element* pobjElement) override
{
cout << pobjElement->getName() << " visitor one visits one" << endl;
}
virtual void visitElementTwo(Element* pobjElement) override
{
cout << pobjElement->getName() << " visitor one visits two" << endl;
}
};
class VisitorTwo : public Visitor
{
public:
virtual void visitElementOne(Element* pobjElement) override
{
cout << pobjElement->getName() << " visitor two visits one" << endl;
}
virtual void visitElementTwo(Element* pobjElement) override
{
cout << pobjElement->getName() << " visitor two visits two" << endl;
}
};
class ElementOne : public Element
{
public:
ElementOne(const string& strName) : Element(strName) {}
virtual void accept(Visitor* pobjVisitor) override
{
pobjVisitor->visitElementOne(this);
}
};
class ElementTwo : public Element
{
public:
ElementTwo(const string& strName) : Element(strName) {}
virtual void accept(Visitor* pobjVisitor) override
{
pobjVisitor->visitElementTwo(this);
}
};
class ObjectStruct
{
public:
void addElement(Element* pobjElement)
{
m_vecElement.push_back(pobjElement);
}
void removeElement(Element* pobjElement)
{
for (auto it = m_vecElement.begin(); it != m_vecElement.end(); ++it)
{
if (*it == pobjElement)
{
m_vecElement.erase(it);
break;
}
}
}
void accept(Visitor* pobjVisitor)
{
for (auto& it : m_vecElement)
{
if (it)
{
it->accept(pobjVisitor);
}
}
}
private:
vector<Element*> m_vecElement;
};
int main()
{
ObjectStruct objObjectStruct;
objObjectStruct.addElement(new ElementOne("彳亍"));
objObjectStruct.addElement(new ElementTwo("行"));
Visitor* pobjVisitorOne = new VisitorOne();
Visitor* pobjVisitorTwo = new VisitorTwo();
objObjectStruct.accept(pobjVisitorOne);
objObjectStruct.accept(pobjVisitorTwo);
return 0;
}
总结:把处理从数据结构中分离,需要数据结构相对稳定
访问者模式
最新推荐文章于 2024-01-19 10:25:31 发布