设计模式C++实现二十三:访问者模式

访问者模式(Visitor):表示一个作用于某个对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

访问者模式适用于数据结构相对稳定的系统。它把数据结构和作用于结构上的操作之间的耦合解脱开,使得操作集合可以相当自由地演化。访问者模式的目的是要把处理从数据结构分离出来。很多系统可以按照算法和数据结构分开,如果这样的系统有比较稳定的数据结构,又有易于变化的算法的话,使用访问者模式就比较合适的,因为访问者模式使得算法操作的增加变得容易。访问者模式的优点就是增加新的操作很容易,因为增加新的操作就意味着增加一个新的访问者。访问者模式将有关的行为集中到一个访问者对象中。

访问者的缺点其实也就是使增加新的数据结构变得困难了。

#ifndef VISITOR_H
#define VISITOR_H
#include<iostream>
#include<string>
#include<list>
using namespace std;
class Man;
class Woman;
class Action
{
public:
	virtual void GetManConclusion(Man man)=0;
	virtual void GetWomanConclusion(Woman woman) = 0;
};
class Person
{
public:
	virtual void Accept(Action* visitor)=0;
};
class Man :public Person
{
public:
	void Accept(Action* visitor)
	{
		visitor->GetManConclusion(*this);
	}
};
class Woman :public Person
{
public:
	void Accept(Action* visitor)
	{
		visitor->GetWomanConclusion(*this);
	}
};

class Success :public Action
{
public:
	void GetManConclusion(Man man)
	{
		cout << "男人成功时,背后多半有一个伟大的女人!\n";
	}
	void GetWomanConclusion(Woman woman)
	{
		cout << "女人成功时,背后多半有一个不成功的男人!\n";
	}
};
class Fail :public Action
{
public:
	void GetManConclusion(Man man)
	{
		cout << "男人失败时,闷头喝酒,谁也不用劝!\n";
	}
	void GetWomanConclusion(Woman woman)
	{
		cout << "女人失败时,眼泪汪汪,谁也劝不了!\n";
	}
};

class FallInLove :public Action
{
public:
	void GetManConclusion(Man man)
	{
		cout << "男人恋爱时,凡事不懂也要装懂!\n";
	}
	void GetWomanConclusion(Woman woman)
	{
		cout << "女人恋爱时,遇事懂也要装作不懂!\n";
	}
};

class ObjectStructure
{
	list<Person *>elements;
public:
	void Attach(Person * ele)
	{
		elements.push_back(ele);
	}
	void Detach(Person * ele)
	{
		elements.remove(ele);
	}
	void Display(Action * ac)
	{
		for each (Person* var in elements)
			var->Accept(ac);

		{

		}
	}
};
#endif

#include "Visitor.h"

int main()
{
	ObjectStructure s;
	Person * p1 = new Man()
	s.Attach(p1);
	s.Attach(new Woman());

	s.Display(new Success);
	s.Display(new Fail);
	s.Detach(p1);
	s.Display(new FallInLove);
	
	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值