#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Visitor;
class Element
{
protected:
string name;
public:
Element(string name)
{
this->name = name;
}
string GetName() const
{
return this->name;
}
virtual void Accept(Visitor *visitor) = 0;
};
class Visitor
{
public:
virtual void Visit(Element* element) = 0;
};
class Friend : public Visitor
{
public:
void Visit(Element* element)
{
cout << "好友访问" << element->GetName() << endl;
}
};
class Stranger : public Visitor
{
public:
void Visit(Element* element)
{
cout << "陌生人访问" << element->GetName() << endl;
}
};
class Zoom : public Element
{
public:
Zoom(string name) : Element(name) {}
virtual void Accept(Visitor *visitor)
{
visitor->Visit(this);
}
};
class Article
{
private:
vector<Element*> vec_element;
public:
void AddElement(Element* element)
{
vec_element.push_back(element);
}
void RemoveElement(Element* element)
{
for (vector<Element*>::iterator it = vec_element.begin(); it != vec_element.end(); )
{
if (*it == element)
{
vec_element.erase(it);
break;
}
it++;
}
}
void Accept(Visitor *visitor)
{
Element *element = NULL;
for (vector<Element*>::iterator it = vec_element.begin(); it != vec_element.end(); it++)
{
element = *it;
element->Accept(visitor);
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Article *pArticles = new Article;
pArticles->AddElement(new Zoom("文章1"));
pArticles->AddElement(new Zoom("文章2"));
pArticles->AddElement(new Zoom("文章3"));
Visitor *pFriend = new Friend;
Visitor *pStranger = new Stranger;
pArticles->Accept(pFriend);
pArticles->Accept(pStranger);
return 0;
}
访问者模式之C++实现