行为型模式之访问者模式

#include<iostream>
#include<list>
using namespace std;

class ParkElement;

class Visitor
{
public:
	virtual void visit(ParkElement*parkelement) = 0;
};

class ParkElement
{
public:
	virtual void accept(Visitor*visitor) = 0;
};

class ParkA :public ParkElement
{
public:
	virtual void accept(Visitor*visitor)
	{
		visitor->visit(this);
	}
};

class ParkB :public ParkElement
{
public:
	virtual void accept(Visitor*visitor)
	{
		visitor->visit(this);
	}
};

class Park :public ParkElement
{
public:
	Park()
	{
		m_list.clear();
	}

	void setPark(ParkElement*parkelement)//管理添加所有公园
	{
		m_list.push_back(parkelement);
	}

	virtual void accept(Visitor*visitor)
	{
		for (list<ParkElement*>::iterator it = m_list.begin(); it != m_list.end(); it++)
		{
			(*it)->accept(visitor);
		}
	}

private:
	list<ParkElement*>m_list;
};

class VisitorA :public Visitor
{
public:
	virtual void visit(ParkElement*parkelement)
	{
		cout << "员工A访问公园A部分!" << endl;
	}
};

class VisitorB :public Visitor
{
public:
	virtual void visit(ParkElement*parkelement)
	{
		cout << "员工B访问公园B部分!" << endl;
	}
};

class ManagerVisitor :public Visitor
{
public:
	virtual void visit(ParkElement*parkelement)
	{
		cout << "领导视察公园!" << endl;
	}
};

void main1()
{
	ParkElement *parkA = new ParkA;
	ParkElement *parkB = new ParkB;

	Visitor*visitorA = new VisitorA;
	Visitor*visitorB = new VisitorB;

	parkA->accept(visitorA);
	parkB->accept(visitorB);
	delete visitorA;
	delete visitorB;
	delete parkA;
	delete parkB;
}

void main2()
{
	Park *park = new Park;
	ParkElement *parkA = new ParkA;
	ParkElement *parkB = new ParkB;
	Visitor *managerVisitor = new ManagerVisitor;

	park->setPark(parkA);
	park->setPark(parkB);

	park->accept(managerVisitor);

	delete managerVisitor;
	delete park;
}

void main()
{
	main2();
	cout << "干活!" << endl;
}

main1运行结果:


main2运行结果:


阅读更多
上一篇行为型模式之备忘录模式
下一篇行为型模式之状态模式
想对作者说点什么? 我来说一句

(行为型模式) Visitor 访问者模式

2009年12月05日 10.89MB 下载

没有更多推荐了,返回首页

关闭
关闭