Visitor模式
一.意图
表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
二.适用性
1.一个对象结构包含很多类对象,它们有不同的接口,而你想对这些对象实施一些依赖于其具体类的操作。
2.需要对一个对象结构中的对象进行很多不同的并且不相关的操作,而你想避免让这些操作“污染”这些对象的类。Vi s i t o r 使得你可以将相关的操作集中起来定义在一个类中。当该对象结构被很多应用共享时,用Vi s i t o r 模式让每个应用仅包含需要用到的操作。
3.定义对象结构的类很少改变,但经常需要在此结构上定义新的操作。改变对象结构类需要重定义对所有访问者的接口,这可能需要很大的代价。如果对象结构类经常改变,那么可能还是在这些类中定义这些操作较好。
三.结构
四.代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <math.h>
#include <qxmlstream.h>
#include <QDomDocument>
#include <QDebug>
#include <QApplication>
#include <windows.h>
#include <QLibrary>
#include <unistd.h>
class CElementLabel;
class CElementButton;
class CVisitor
{
public:
virtual void VisitDrawLabel(CElementLabel* eleLbl);
virtual void VisitDrawButton(CElementButton* eleBtn);
};
class CElement
{
public:
virtual void Accept(CVisitor* visitor);
};
class CVisitorLabel : public CVisitor
{
public:
virtual void VisitDrawLabel(CElementLabel* eleLbl);
virtual void VisitDrawButton(CElementButton* eleBtn);
};
class CVisitorButton : public CVisitor
{
public:
virtual void VisitDrawLabel(CElementLabel* eleLbl);
virtual void VisitDrawButton(CElementButton* eleBtn);
};
class CElementLabel : public CElement
{
public:
CElementLabel(QString name)
{
m_name = name;
}
QString GetName()
{
return m_name;
}
void Accept(CVisitor* visitor);
private:
QString m_name;
};
class CElementButton : public CElement
{
public:
CElementButton(QString name)
{
m_name = name;
}
QString GetName()
{
return m_name;
}
void Accept(CVisitor* visitor);
private:
QString m_name;
};
void CVisitorLabel::VisitDrawButton(CElementButton *eleBtn)
{
}
void CVisitorLabel::VisitDrawLabel(CElementLabel *eleLbl)
{
qDebug("Draw Label");
}
void CVisitorButton::VisitDrawButton(CElementButton *eleBtn)
{
qDebug("Draw Button");
}
void CVisitorButton::VisitDrawLabel(CElementLabel *eleLbl)
{
}
void CElementLabel::Accept(CVisitor* visitor)
{
visitor->VisitDrawLabel(this);
}
void CElementButton::Accept(CVisitor *visitor)
{
visitor->VisitDrawButton(this);
}
class CObjectStructure
{
public:
CObjectStructure()
{
m_pVElement.clear();
}
void Attach(CElement* element)
{
m_pVElement.push_back(element);
}
void Detach(CElement* element){}
void Accept(CVisitor* visitor)
{
for(int i = 0; i < m_pVElement.size(); i++)
{
m_pVElement[i]->Accept(visitor);
}
}
private:
std::vector<CElement*> m_pVElement;
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
CElementLabel* label1 = new CElementLabel("Label 1");
CElementLabel* label2 = new CElementLabel("Label 2");
CElementButton* btn1 = new CElementButton("Btn 1");
CElementButton* btn2 = new CElementButton("Btn 2");
CVisitor* label = new CVisitorLabel();
CVisitor* button = new CVisitorButton();
CObjectStructure* os = new CObjectStructure();
os->Attach(label1);
os->Attach(label2);
os->Attach(btn1);
os->Attach(btn2);
os->Accept(label);
return app.exec();
}